0

I sorted lists within list on python. but I need to count list elements too. following list:

fruit = [
    ['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'],
    ['Grape', 'B+'], ['Grape', 'C+']
]

result:

{'Apple':{'total':3, 'S+':2, 'B+':1}, 'Grape':{'total':2, 'B+':1, 'C+':1}}

I got above result through several for and while. but I want simple way. Is there beautiful and simple way to get result above thing ?

0

3 Answers 3

1

itertools.groupby is fun.

>>> result = {}
>>> for k, v in groupby(fruit,lambda x:x[0]):
...     value = list(v)
...     result[k] = {'total':len(value)}
...     for i,j in groupby(value, lambda x:x[1]):
...         result[k].update({i:len(list(j))})

Output:

{'Grape': {'total': 2, 'C+': 1, 'B+': 1}, 'Apple': {'total': 3, 'S+': 2, 'B+': 1}}

N.B.

Though, not needed here, it is always wise to sort the collection before applying groupby. For this example:

fruit = sorted(fruit, key= lambda x:(x[0],x[1]))
Sign up to request clarification or add additional context in comments.

Comments

0

Something approaching what you want, using collections.defaultdict and collections.Counter.

I tried to make it as pythonic as possible.

import collections

fruit = [
    ['Apple', 'S+'], ['Apple', 'S+'], ['Apple', 'B+'],
    ['Grape', 'B+'], ['Grape', 'C+']
]


d = collections.defaultdict(lambda : [collections.Counter(),0])

for k,v in fruit:
    d[k][0][v]+=1
    d[k][1]+=1

print(dict(d))  # convert to dict for readability when printing

result:

{'Grape': [Counter({'B+': 1, 'C+': 1}), 2], 'Apple': [Counter({'S+': 2, 'B+': 1}), 3]}

details:

  • create a dictionary that defaults to creating a 2-element list when key doesn't exist. This element list is made of a collections.Counter object and an integer (for global count)
  • loop on the "tuples", and count elements and total.

Comments

0
unique, counts = numpy.unique(fruits, return_counts=True)

return_counts was added to unique in numpy 1.9.0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.