Question

Hi all I have a problem in Python. I am attempting to make a new list using two returns from previous functions. I would like to take each element in the element list and check to see if it is the first entry in at least one of the duples. If it is, append the corresponding number to the 'vector' list. If the element does not appear in the duple list then I would append a '0'.

Example: Using these two lists:

duple_list=[('C', 1), ('H', 4)]

element_list=['C', 'H', 'N']

should return a vector like:

[1, 4, 0]

my current code returns this instead:

[1, 0, 4, 0, 0]

current code:

for element in element_list:
    for duple in duple_list:
           if element==duple[0]:
              vector.append(duple[1])
              break
          if element!=duple[0]:
              vector.append(0)
return vector

I know why my code isn't working, but I don't know which tool I should be using instead/ what I should do differently.

Was it helpful?

Solution

>>> [dict(duple_list).get(e, 0) for e in element_list]
[1, 4, 0]

Steps without list comprehension. Create dict from list of tuples:

>>> duple_dict = dict(duple_list)
>>> duple_dict
{'H': 4, 'C': 1}

and check each element from element_list for containing in duple_dict:

>>> vector = []
>>> for element in element_list:
       if element in dict(duple_dict):
           vector.append(duple_dict[element])
       else:
           vector.append(0)

>>> vector
[1, 4, 0]
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top