count occurrence of a list in a list of lists

前端 未结 3 1710
我在风中等你
我在风中等你 2020-11-28 15:53

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 i

相关标签:
3条回答
  • 2020-11-28 16:26

    You can use collections.Counter - a dict subclass - to take the counts. First, convert the sublists to tuples to make them usable (i.e. hashable) as dictionary keys, then count:

    from collections import Counter
    
    count = Counter(map(tuple, A))
    
    0 讨论(0)
  • 2020-11-28 16:39

    Just use Counter from collections:

    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))
    
    0 讨论(0)
  • 2020-11-28 16:46

    Depending on your output, you can loop through a set of your list and print each item with its count() from the original list:

    for x in set(map(tuple, A)):
        print '{} = {}'.format(x, A.count(list(x)))
    
    0 讨论(0)
提交回复
热议问题