简体   繁体   English

计算列表列表中列表的出现次数

[英]count occurrence of a list in a list of lists

Python Python

I have a list of lists.我有一个列表列表。 like

A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

I want to count how many times each list occurred in the main list.我想计算每个列表在主列表中出现的次数。

My output should be like我的输出应该像

[x,y] = 2
[a,b] = 2
[c,f] = 1 
[e,f] = 1

Just use Counter from collections :只需使用collections中的Counter

from collections import Counter
A = [[x,y],[a,b],[c,f],[e,f],[a,b],[x,y]]

new_A = map(tuple, A) #must convert to tuple because list is an unhashable type

final_count = Counter(new_A)


#final output:

for i in set(A):
   print i, "=", final_count(tuple(i))

You can use collections.Counter - a dict subclass - to take the counts.您可以使用collections.Counter - 一个 dict 子类 - 来进行计数。 First, convert the sublists to tuples to make them usable (ie hashable) as dictionary keys, then count:首先,将子列表转换为元组,使它们可用作(即可散列)字典键,然后计数:

from collections import Counter

count = Counter(map(tuple, A))

You can also use pandas for cleaner code:您还可以使用 pandas 来获得更简洁的代码:

pd.Series(A).explode().value_counts()

Depending on your output, you can loop through a set of your list and print each item with its count() from the original list :根据您的输出,您可以loopset list并打印每个项目及其原始listcount()

for x in set(map(tuple, A)):
    print '{} = {}'.format(x, A.count(list(x)))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM