Consider a list as follows:
entry = [ 'document1', 'document2', 'document1', 'document2' ]
Now if I run the following piece of code:
for i in entry:
print i + "has index" + entry.index(i)
It gives the output as
document1 has index 0
document2 has index 1
document1 has index 0
document2 has index 1
But the output should be:
document1 has index 0
document2 has index 1
document1 has index 2
document2 has index 3
Can anyone help me what should I edit in this code?
PS: I would like to use a function rather than introducing a dummy variable which is incremented along with the list.
You could write your own function (which uses enumerate) and use it in your code - then your code won't be cluttered with extraneous distrations:
from collections import defaultdict
def element_indices(entry):
result = defaultdict(list)
for ndx, element in enumerate(entry):
result[element].append(ndx)
return result
Usage:
entry = [ 'document1', 'document2', 'document1', 'document2' ]
for element, indices in element_indices(entry).items():
print '{} is found at indices {}'.format(element, indices)
# >>>
# document1 is found at indices [0, 2]
# document2 is found at indices [1, 3]
# >>>
As the comments suggest, you want enumerate()
:
for n, item in enumerate(entry):
print item + " has index " + str(n)
This is the standard, idiomatic way to do what you want in Python.
Your desire to avoid using a "dummy" variable, as you call it, is perplexing; If there is some particular reason for that restriction, it would be helpful if you mentioned that in your question.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.