列表列表中元素的频率
Frequency of elements in a list of list
我的目标是计算列表中单词的频率。所以,我有:
list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]
我的目标是这样的:
x:3, y:3, w:2, z:1
您可以使用 Counter
:
>>> from collections import Counter
>>> Counter(elem for sub in list_1 for elem in sub)
Counter({'x': 3, 'y': 3, 'w': 2, 'z': 1})
你可以这样做:
list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]
freq = {}
for i in list_1:
for j in i:
try:
freq[j] += 1
except KeyError:
freq[j] = 1
print(freq)
我的目标是计算列表中单词的频率。所以,我有:
list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]
我的目标是这样的:
x:3, y:3, w:2, z:1
您可以使用 Counter
:
>>> from collections import Counter
>>> Counter(elem for sub in list_1 for elem in sub)
Counter({'x': 3, 'y': 3, 'w': 2, 'z': 1})
你可以这样做:
list_1 = [['x', 'y', 'z'], ['x', 'y', 'w'], ['w', 'x', 'y']]
freq = {}
for i in list_1:
for j in i:
try:
freq[j] += 1
except KeyError:
freq[j] = 1
print(freq)