保持字典中的命中数

时间:2017-07-10 14:56:54

标签: python dictionary

我有一个(唯一的)单词列表:

words = [store, worry, periodic, bucket, keen, vanish, bear, transport, pull, tame, rings, classy, humorous, tacit, healthy]

我想用两个不同的列表列表(具有相同的范围)进行交叉检查,同时计算点击次数。

l1 = [[terrible, worry, not], [healthy], [fish, case, bag]]
l2 = [[vanish, healthy, dog], [plant], [waves, healthy, bucket]]

我正在考虑使用字典并将该单词作为键,但是对于点击次数需要两个“值”(每个列表一个)。 所以输出将是这样的:

{"store": [0, 0]}
{"worry": [1, 0]}
...
{"healthy": [1, 2]}

这样的事情怎么样? 提前谢谢!

2 个答案:

答案 0 :(得分:2)

对于您的字典示例,您只需迭代每个列表并将其添加到字典中,如下所示:

my_dict = {}
for word in l1:
    if word in words: #This makes sure you only work with words that are in your list of unique words
        if word not in my_dict:
            my_dict[word] = [0,0]
        my_dict[word][0] += 1
for word in l2:
    if word in words:
        if word not in my_dict:
            my_dict[word] = [0,0]
        my_dict[word][1] += 1

(或者你可以让重复的代码成为传递参数列表,字典和索引的函数,这样你重复的行数就会减少)

如果您的列表在示例中是2d,那么您只需将for循环中的第一次迭代更改为2d。

my_dict = {}
for group in l1:
    for word in group:
        if word in words: 
            if word not in my_dict:
                my_dict[word] = [0,0]
            my_dict[word][0] += 1
for group in l2
    for word in group:
        if word in words:
            if word not in my_dict:
                my_dict[word] = [0,0]
            my_dict[word][1] += 1

虽然如果你只是想知道共同的单词,也许集合也可以是一个选项,因为你有集合中的联合运算符可以方便地查看所有单词,但是集合可以消除重复,所以如果计数是必要的,那么这个集合不是一个选项。

答案 1 :(得分:2)

您可以使用itertools展平列表,然后使用字典理解:

from itertools import chain
words = [store, worry, periodic, bucket, keen, vanish, bear, transport, pull, tame, rings, classy, humorous, tacit, healthy]

l1 = [[terrible, worry, not], [healthy], [fish, case, bag]]
l2 = [[vanish, healthy, dog], [plant], [waves, healthy, bucket]]

l1 = list(chain(*l1))

l2 = list(chain(*l2))

final_count = {i:[l1.count(i), l2.count(i)] for i in words}