Python 我们有嵌套列表创建字典关键字作为单词列表,以及它们作为值出现的次数
实际代码为:Python 我们有嵌套列表创建字典关键字作为单词列表,以及它们作为值出现的次数,python,python-2.7,Python,Python 2.7,实际代码为: big_list = [[['one', 'two'], ['seven', 'eight']], [['nine', 'four'], ['three', 'one']], [['two', 'eight'], ['seven', 'four']], [['five', 'one'], ['four', 'two']], [['six', 'eight'], ['two', 'seven']], [['three', 'five'], ['one', 'six']], [['ni
big_list = [[['one', 'two'], ['seven', 'eight']], [['nine', 'four'], ['three', 'one']], [['two', 'eight'], ['seven', 'four']], [['five', 'one'], ['four', 'two']], [['six', 'eight'], ['two', 'seven']], [['three', 'five'], ['one', 'six']], [['nine', 'eight'], ['five', 'four']], [['six', 'three'], ['four', 'seven']]]
word_counts = {}
for n in big_list:
for i in big_list:
if n == i:
word_counts[i] = word_counts[i] + 1
print(word_counts)
错误为:
不可损坏类型:第8行的“列表”
预期结果:
像那样
所以请帮我找到正确的解决方案
可以使用以展平嵌套列表并计算每个元素出现的次数:
from collections import Counter
from itertools import chain
Counter(chain(*chain(*big_list)))
输出
对于没有导入的解决方案,您可以执行以下操作:
d = {}
for i in big_list:
for j in i:
for k in j:
if not d.get(k):
d[k] = 1
else:
d[k] += 1
print(d)
# {'one': 4, 'two': 4, 'seven': 4, 'eight': 4, 'nine': 2,
# 'four': 5, 'three': 3, 'five': 3, 'six': 3}
您可以尝试以下代码:
big_list = [[['one', 'two'], ['seven', 'eight']], [['nine', 'four'], ['three', 'one']], [['two', 'eight'], ['seven', 'four']], [['five', 'one'], ['four', 'two']], [['six', 'eight'], ['two', 'seven']], [['three', 'five'], ['one', 'six']], [['nine', 'eight'], ['five', 'four']], [['six', 'three'], ['four', 'seven']]]
word_counts= {}
for ch in big_list:
for word in ch:
for req in word:
if req not in word_counts:
word_counts[req] = 0
word_counts[req]+=1
print(word_counts)
我们可以不使用module/libaray吗?让我发布另一个可选的if嵌套字典,而不是列表,那么什么时候如何计算值相同的键,但不同的子字典我不确定你的意思@MahendraSeervi。。。不幸的是,这似乎是一个不同的问题,所以我建议你问一个新问题,你肯定会很快得到答案:-)Hii@yatu如何使用循环和打印键和值迭代嵌套字典请阅读以改进答案的格式,并查看以改进答案。
big_list = [[['one', 'two'], ['seven', 'eight']], [['nine', 'four'], ['three', 'one']], [['two', 'eight'], ['seven', 'four']], [['five', 'one'], ['four', 'two']], [['six', 'eight'], ['two', 'seven']], [['three', 'five'], ['one', 'six']], [['nine', 'eight'], ['five', 'four']], [['six', 'three'], ['four', 'seven']]]
word_counts= {}
for ch in big_list:
for word in ch:
for req in word:
if req not in word_counts:
word_counts[req] = 0
word_counts[req]+=1
print(word_counts)