获取列表中每个元素首次出现的索引? [英] Get indexes for first occurrence of each element in a list?
本文介绍了获取列表中每个元素首次出现的索引?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个大约90k元素的列表(大约670个唯一元素).我想获取每个值的第一次出现的索引.我刚刚尝试过这样的列表理解:
I have a list of about 90k elements (about 670 unique). I would like to get the indexes for the first occurrence of each value. I have just tried a list comprehension like this:
In: [["foo", "bar", "baz", "bar", "foo"].index(x) for x in ["foo", "bar", "baz", "bar", "foo"]]
Out: [0, 1, 2, 1, 0]
这可行,但是要花几分钟才能在我的机器上运行.什么是更好(更快)的方法?
This works, but it takes a couple of minutes to run on my machine. What is a better (faster) way to do this?
推荐答案
我认为您只想使用 enumerate
(除非您想要列表中每个项目的第一个出现):
I think you just want to use enumerate
(unless you want the first occurrence of each item in the list):
strings = ["foo", "bar", "baz", "bar", "foo"]
for index, value in enumerate(strings):
print index, value
输出
0 foo
1 bar
2 baz
3 bar
4 foo
例如,如果要使用 1 bar
而不是 3 bar
,则可以维护找到的字符串的字典:
If you wanted, for example, 1 bar
instead of 3 bar
, you can maintain a dictionary of found strings:
for index, value in enumerate(strings):
if value not in d:
d[value] = index
for value in strings:
print value, d[value]
这篇关于获取列表中每个元素首次出现的索引?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文