我有以下代码:
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}}
这意味着关键应该是我列表中所有不同的单词。值是所有单词的计数,仅包括键出现的列表。在
我不知道有什么函数可以实现这个特性,因此我写了一个代码片段,它至少适用于我尝试过的案例,尽管解决方案不是很优雅。它包括笨拙嵌套的for循环和if语句。我相信可以找到更好的解决办法。在
问题可以分为两个部分:获取唯一键和相应的值。我使用
Counter()
本身来获得密钥很容易,但是set()
也可以使用。得到相应的值是一个棘手的部分。为此,我取了每个唯一的键并在字典中迭代,以找到该键属于哪些字典。当找到一个字典时,取字典中的其他键,在所有有键的字典上迭代,以求出计数器的总和。在以下是一些测试用例:
^{pr2}$相关问题 更多 >
编程相关推荐