1
a=[[2, 5, 21,],
  [2, 9, 14,],
  [2, 22, 32],
  [3, 10, 13],
  [3, 10, 13]
  [3, 10, 13]]

for i in range(len(a)):
  cnt=1                  #count
for j in range(i, len(a)):

    if (i==j):
        continue
    elif (len(set(a[i])&set(a[j]))==6):
        cnt+=1
        print('\t{:2} {:2} {:2} {:2} {:2} {:2}, number {:2} '.format(*a[i],cnt))
    else:
        pass

The code i want to create is below

[3, 10, 13], num 3

How to count the list of list?

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
kosskoss
  • 29
  • 4

1 Answers1

1

You can use collections.Counter for it if you convert the inner list into tuples (lists are not hashable - dicts need hashable keys - f.e tuples):

from collections import Counter

a=[[2, 5, 21,],
  [2, 9, 14,],
  [2, 22, 32],
  [3, 10, 13],
  [3, 10, 13],
  [3, 10, 13]]

c = Counter( map(tuple,a) )   # shorter notation for: ( tuple(item) for item in a) )

# extract all (key,value) tuples with values > 1
for what, how_much in  (x for x in c.most_common() if x[1] > 1):  

    # 3.6 string interpol, use  "{} num {}".format(list(what),how_much) else
    print(f"{list(what)} num {how_much}") 

Output:

[3, 10, 13] num 3

You could also use itertools.groupby() but you would have to sort the list first:

import itertools
# to make groupby work
a.sort()

for key,items in itertools.groupby(a):
    how_much = len(list(items))
    if how_much > 1:
        print(key, "num", how_much) 

Same result. The itertools usage was loosly inspired by this answer to "how to remove dupes from list of list" when looking for dupes to this OP)

Patrick Artner
  • 50,409
  • 9
  • 43
  • 69
  • 1
    @pygo ty. For big lists the Counter - approach might be faster though - depends on if sort() and groupby() takes longer in total then creating the intermerdiate tuples needed as keys for Counter - both are valid approaches. – Patrick Artner Oct 28 '18 at 15:33
  • @ Patrick, well said, i reproduced with itertool but i saw you already given that with 2 distinct approaches which looks nice, my +1. – Karn Kumar Oct 28 '18 at 15:35
  • 1
    `Counter(map(tuple, a))` also works. You can also use a generator expression: `(x for x in c.most_common() if x[1] > 1)`. – jpp Oct 28 '18 at 15:53
  • @jpp the map is nice, I am unclear to what advantage using a generator expression `for what,how_much in (x for x in c.most_common() if x[1] > 1):` has over `for what, how_much in [x for x in c.most_common() if x[1] > 1]:` would have - would'nt the generator have to be evaluated in total as well? Is that still better then creating the list-object? – Patrick Artner Oct 28 '18 at 15:56
  • 1
    @PatrickArtner, No, I don't think so. The generator expression is *lazy*, so a full list or tuple of values is never produced at any point. Only when you feed the gen expr to `list` or `tuple` etc does it get *exhausted* in one go. – jpp Oct 28 '18 at 15:58