我不知道任何实现此功能的函数,因此我编写了一个至少适用于我尝试过的情况的 sn-p,尽管解决方案不是很优雅。它包括笨拙地嵌套的 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)
这里有一些测试用例:
>>> 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}}