python comprehension for循环使用if语句和

时间:2016-01-29 01:27:17

标签: python list-comprehension

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)。

如何理解能做同样的事情?

1 个答案:

答案 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]}