如何在集合中使用Counter来计算Python中不同列表中的单词数?

2024-09-24 10:29:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下代码:

def myFunc(word):
    for id, sList in enumerate(word):
        counts = Counter(sList)
        print(counts)


myFunc([['Apple', 'Orange', 'Banana'], ["Banana", "Orange"]])

输出:

^{pr2}$

这太棒了。但是如果我想要这样的输出字典呢:

{'Apple': {'Orange':1, 'Banana': 1}, 'Orange': {'Apple':1, 'Banana':2},
  'Banana': {'Apple':1, 'Orange':2}}

这意味着关键应该是我列表中所有不同的单词。值是所有单词的计数,仅包括键出现的列表。在


Tags: 代码inidapple列表fordefmyfunc
1条回答
网友
1楼 · 发布于 2024-09-24 10:29:29

我不知道有什么函数可以实现这个特性,因此我写了一个代码片段,它至少适用于我尝试过的案例,尽管解决方案不是很优雅。它包括笨拙嵌套的for循环和if语句。我相信可以找到更好的解决办法。在

问题可以分为两个部分:获取唯一键和相应的值。我使用Counter()本身来获得密钥很容易,但是set()也可以使用。得到相应的值是一个棘手的部分。为此,我取了每个唯一的键并在字典中迭代,以找到该键属于哪些字典。当找到一个字典时,取字典中的其他键,在所有有键的字典上迭代,以求出计数器的总和。在

from collections import Counter
# countered_list contains Counter() of individual lists.
countered_list = []
# Gives the unique keys.
complete = []
def myFunc(word):
    for each_list in word:
        complete.extend(each_list)
        countered_list.append(Counter(each_list))

    # set() can also be used instead of Counter()
    counts = Counter(complete)
    output = {key:{} for key in counts}

    # Start iteration with each key in count => key is unique
    for key in counts:
        # Iterate over the dictionaries in countered_list
        for each_dict in countered_list:
            # if key is in each_dict then iterate over all the other keys in dict
            if key in each_dict:
                for other_keys in each_dict:
                    # Excludes the key
                    if key != other_keys:
                        temp = 0
                        # Now iterate over all dicts for other_keys and add the value to temp
                        for every_dict in countered_list:
                            # Excludes the dictionaries in which key is not present.
                            if key in every_dict:
                                temp += every_dict[other_keys]
                        output[key][other_keys] = temp

    print(output)

以下是一些测试用例:

^{pr2}$

相关问题 更多 >