Python 在字典中保留命中数

Python 在字典中保留命中数,python,dictionary,Python,Dictionary,我有一个(独特的)单词列表: 我想交叉检查两个不同的列表(范围相同),同时计算点击数 l1 = [[terrible, worry, not], [healthy], [fish, case, bag]] l2 = [[vanish, healthy, dog], [plant], [waves, healthy, bucket]] 我曾考虑使用字典,并假设该单词为键,但需要两个“值”(每个列表一个)来表示点击次数。 因此,输出类似于: {"store": [0, 0]} {"worry":

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

我想交叉检查两个不同的列表(范围相同),同时计算点击数

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]}
这个工作怎么样?
提前谢谢你

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

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
(或者,您可以将重复的代码设置为传递参数列表、字典和索引的函数,这样您可以重复更少的行)

如果列表是二维的(如示例中所示),则只需将for循环中的第一次迭代更改为二维

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

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

您可以使用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}

听起来你已经把基本结构搞定了。你到底遇到了什么问题?让你的生活更轻松,使用
集合列表。相反,使用Counter
。@glibdud,我想我的想法是对的,但我可能缺少某种比迭代和添加更简单的方法或解决方法。。。就像托比亚斯现在说的。。。我也去看看!谢谢Davy,我想我无法想象“列表是一个值”,但它工作得非常完美。集合不是你说的选项,因为我需要点击数!当然@Ajax1234的itertools示例更有效,但如果您发现无法使用
,则可以将此词典作为一种工具放在您的后口袋中。祝你好运谢谢Ajax,它也可以完美地工作。短小而优雅。该链也将非常方便,以简化我以前的一些代码!很高兴我能帮忙!
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}