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]
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
outputs
0 foo
1 bar
2 baz
3 bar
4 foo
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]