if n,item in enumerate(list):
if item=='pattern':
dict[item]=[] #basically I need a step to initialize the value of that dictionary as a list.
dict[item].append(n)
一旦dict的每个键都有一个值作为列表,我可以将与项目相关的东西附加到该列表中(在这种情况下只是迭代编号n)。
如何理解能做同样的事情?
答案 0 :(得分:1)
我想你在询问collections.defaultdict
:
d = defaultdict(list)
for index, key in enumerate(l):
if key == "pattern":
d[key].append(index)
示例:
from collections import defaultdict
l = ["test1", "pattern", "test2", "pattern"]
d = defaultdict(list)
for index, key in enumerate(l):
if key == "pattern":
d[key].append(index)
print(d)
打印:
{'pattern': [1, 3]}