Python:获取列表中字典项的索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4573875/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Get index of dictionary item in list
提问by dkgirl
I have a list li:
我有一个列表 li:
[
{name: "Tom", age: 10},
{name: "Mark", age: 5},
{name: "Pam", age: 7}
]
I want to get the index of the item that has a certain name. For example, if I ask for "Tom" it should give me: 0. "Pam" should give me 2.
我想获取具有特定名称的项目的索引。例如,如果我要求“Tom”,它应该给我:0。“Pam”应该给我 2。
回答by satoru
You may index the dicts by name
您可以通过以下方式索引字典 name
people = [ {'name': "Tom", 'age': 10}, {'name': "Mark", 'age': 5} ]
name_indexer = dict((p['name'], i) for i, p in enumerate(people))
name_indexer.get('Tom', -1)
回答by John La Rooy
>>> from operator import itemgetter
>>> map(itemgetter('name'), li).index('Tom')
0
>>> map(itemgetter('name'), li).index('Pam')
2
If you need to look up a lot of these from the same list, creating a dict as done in Satoru.Logic's answer, is going to be a lot more efficent
如果您需要从同一个列表中查找很多这些,按照 Satoru.Logic 的答案创建一个 dict 会更有效率

