如何计算列表的元素频率

时间:2015-02-25 01:36:00

标签: python list hash

我有一份3克的清单。示例输入列表如下所示:

  

A = [[''','big','bang'],['big','bang','theory'],...,['the','big','bang' ]

如何计算这些列表的频率(出现次数)? Python抱怨列表不可清除。

对于目前的情况,我希望得到

dict[['the','big','bang'] = 2
dict[['big','bang','theory']] = 1

谢谢,

4 个答案:

答案 0 :(得分:2)

列表不可清除,这就是为什么你不能把它们作为字典的键。将内部列表转换为元组,以便您可以使用dict进行计数;甚至更好,使用Counter

from collections import Counter
A = [['the','big','bang'],['big','bang','theory'],['the','big','bang']]
cnt = Counter(map(tuple, A))
for k, v in cnt.iteritems():
    print list(k), v

输出:

['big', 'bang', 'theory'] 1
['the', 'big', 'bang'] 2

答案 1 :(得分:1)

如果您的内部列表可能是元组,例如:

A = [('the', 'big', 'bang'), ('big', 'bang', 'theory'), ('the', 'big', 'bang')]

你可以这样做:

result = {a:A.count(a) for a in set(A)} # dict comprehension
print result
{('big', 'bang', 'theory'): 1, ('the', 'big', 'bang'): 2}

答案 2 :(得分:0)

您可以使用字典理解在一行中执行此操作:

data = {i: A.count(list(i)) for i in set([tuple(j) for j in A])}

答案 3 :(得分:0)

# order of individual lists matters
A = [ ['the','big','bang'],['big','bang','theory'],['the','big','bang']]
x = {}
for val in A:
    #val.sort() uncomment this if order within sublists does not matter
    x[str(val)] = x.setdefault(str(val), 0) + 1
print x