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

标签 python python-3.x collections count counter

我有以下代码:

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


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

输出:

Counter({'Apple': 1, 'Orange': 1, 'Banana': 1})
Counter({'Banana': 1, 'Orange': 1})

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

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

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

最佳答案

我不知道有任何函数可以实现此功能,因此我编写了一个至少适用于我尝试过的情况的代码片段,尽管解决方案不是很优雅。它包括笨拙的嵌套 for 循环和 if 语句。我相信可以找到更好的解决方案。

问题可以分为两部分:获取唯一键和对应的值。获取 key 很容易,我使用了 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)

以下是一些测试用例:

>>> new_list = [['a','a'],['b','b'],['c','c']]
>>> myFunc(new_list)
{'a': {}, 'c': {}, 'b': {}}
>>> new_list = [['a','a'],['b','b'],['c','c','a','a']]
>>> myFunc(new_list)
{'a': {'c': 2}, 'c': {'a': 2}, 'b': {}}
>>> new_list = [['a','a'],['b','b','a'],['c','c','a','a']]
>>> myFunc(new_list)
{'a': {'c': 2, 'b': 2}, 'c': {'a': 2}, 'b': {'a': 1}}
>>> new_list = [['ab','ba'],['ba','ab','ab'],['c','c','ab','ba']]
>>> myFunc(new_list)
{'c': {'ab': 1, 'ba': 1}, 'ab': {'c': 2, 'ba': 3}, 'ba': {'c': 2, 'ab': 4}}

关于python - 如何在Python中使用集合中的Counter来计算不同列表中的单词数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49723269/

相关文章:

python - Python中的产量中断

python - 连接提交函数 Python

java - 将枚举转换为集合/列表

python - 在日志记录模块的 RotatingFileHandler 中,如何将 backupCount 设置为几乎无限的数字

python - Pandas - 按日期计算不同的值 - 更有效的方法?

regex - python中将所有类型的换行符替换为 "\n"

python - 将特定单词附加到单独行上的其他单词

c# - 从可枚举的内容构建 C# 列表

powershell - 如何从具有包含特定文本的任何属性的集合中选择对象,并且仅输出这些特定属性?

Python: eval string with\n 最后