简体   繁体   中英

Find a strings location in a list - Python

If I have a series of lists in a dictionary (for example):

{'Name': ['Thomas', 'Steven', 'Pauly 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 eg

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM