Find a strings location in a list - Python
If I have a series of lists in a dictionary (for example):
{'Name': ['Thomas', 'Steven', 'Pa开发者_C百科uly D'], 'Age': [30, 50, 29]}
and I want to find the strings position so I can then get the same position from the other list.
So e.g.
if x = 'Thomas' #is in position 2:
y = dictionary['Age'][2]
Store it in the proper structure in the first place.
D = dict(zip(dictionary['Name'], dictionary['Age']))
print D['Thomas']
i = dictionary['Name'].index('Thomas')
y = dictionary['Age'][i]
However, index
performs a linear search, which could be slow for a large list. In other cases similar to this, I've used a pattern like this:
Person = collections.namedtuple('Person', ['Name', 'Age'])
dictionary = {'Thomas': Person('Thomas', 30), 'Steven': Person('Steven', 50), 'Pauly D': Person('Pauly D', 29)}
You could do the same thing with a dict if you needed the records to be different length. Either way, storing it like this will help accessing records be faster.
You want to use .index()
d = {'Name': ['Thomas', 'Steven', 'Pauly D'], 'Age': [30, 50, 29]}
position = d['Name'].index('Steven')
age = d['Age'][position]
or age = d['Age'][d['Name'].index('Steven')]
more densely.
infoDict = {
'Name': ['Thomas', 'Steven', 'Pauly D'],
'Age': [30, 50, 29]
}
def getAge(name, d):
offs = d['Name'].index(name)
return d['Age'][offs]
getAge('Thomas', infoDict)
精彩评论