简体   繁体   English

在列表中查找字符串位置-Python

[英]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. 但是, index执行线性搜索,对于大列表而言可能很慢。 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. 如果您需要不同长度的记录,则可以使用dict执行相同的操作。 Either way, storing it like this will help accessing records be faster. 无论哪种方式,这样存储都将有助于更快地访问记录。

You want to use .index() 您想使用.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. age = d['Age'][d['Name'].index('Steven')]更密集。

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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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