![](/img/trans.png)
[英]Using a for loop to find the location of all strings in a list (Python 2.7)
[英]Find a strings location in a list - Python
如果我在字典中有一系列列表(例如):
{'Name': ['Thomas', 'Steven', 'Pauly D'], 'Age': [30, 50, 29]}
我想找到字符串位置,這樣我就可以從其他列表中獲得相同的位置。
所以例如
if x = 'Thomas' #is in position 2:
y = dictionary['Age'][2]
首先將其存儲在適當的結構中。
D = dict(zip(dictionary['Name'], dictionary['Age']))
print D['Thomas']
i = dictionary['Name'].index('Thomas')
y = dictionary['Age'][i]
但是, index
執行線性搜索,對於大列表而言可能很慢。 在與此類似的其他情況下,我使用了這樣的模式:
Person = collections.namedtuple('Person', ['Name', 'Age'])
dictionary = {'Thomas': Person('Thomas', 30), 'Steven': Person('Steven', 50), 'Pauly D': Person('Pauly D', 29)}
如果您需要不同長度的記錄,則可以使用dict執行相同的操作。 無論哪種方式,這樣存儲都將有助於更快地訪問記錄。
您想使用.index()
d = {'Name': ['Thomas', 'Steven', 'Pauly D'], 'Age': [30, 50, 29]}
position = d['Name'].index('Steven')
age = d['Age'][position]
或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.