考虑如下列表:
entry = [' document1',' document2',' document1',' document2' ]
现在,如果我运行以下代码:
for i in entry:
print i + "has index" + entry.index(i)
它将输出显示为
document1 has index 0
document2 has index 1
document1 has index 0
document2 has index 1
但输出应该是:
document1 has index 0
document2 has index 1
document1 has index 2
document2 has index 3
任何人都可以帮助我在这段代码中编辑什么?
PS:我想使用一个函数,而不是引入一个随列表一起递增的虚拟变量。
答案 0 :(得分:1)
您可以编写自己的函数(使用枚举)并在代码中使用它 - 然后您的代码不会被无关的注册混乱:
from collections import defaultdict
def element_indices(entry):
result = defaultdict(list)
for ndx, element in enumerate(entry):
result[element].append(ndx)
return result
用法:
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]
# >>>