Langfao Langfao - 1 year ago 75
Python Question

How do I make the elements in one list equal the elements of the other list with loops?

So I'm trying to define a function so that the elements of a list

elements = ['H', 'N', 'C', 'O']

equal to the elements in another list in the same positions

molarMass = [1.00794, 14.0067, 12.0107, 15.9994]

So that H = 1.00794, N = 14.0067, etc..

trying to define a function example:

that when used will look like this

and it returns the corresponding element from the first list and match with the element in the other list that is in the same position
Not sure how to even begin with that.

Answer Source

You could bind them with dictionary comprehension

    elements = ['H', 'N', 'C', 'O']
    molarMass = [1.00794, 14.0067, 12.0107, 15.9994]

    ElementToMolar = {elements[x]:molarMass[x] for x in range(len(elements))}

    for x in ElementToMolar:
        print (x, ElementToMolar[x])

Which outputs:

    O 15.9994
    H 1.00794
    N 14.0067
    C 12.0107

Or if you want to abstract it with operations and use / interact with the data further, probably should use a class?

elements = ['H', 'N', 'C', 'O']
molarMass = [1.00794, 14.0067, 12.0107, 15.9994]

class Element(object):
    def __init__(self, Name, Mass):
        self.Name = Name
        self.Mass = Mass

    def __str__(self):
        return "{0.Name} = {0.Mass}".format(self)

H = Element("H", 1.00794)
N = Element("N", 14.0067)

print (H, N)

Which outputs: H = 1.00794 N = 14.0067

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download