Arranging a list into list of list in python

Viewed 34

I have a python list of fruits

alist=["orange","mango","orange","orange","banana","mango"]

I want to group the different types of fruits into different list

blist=[["orange","orange","orange"],["mango","mango"],["banana"]]

My current solution is too bulky. I create 3 empty list and populate each list with a for loop. That is:

>>>oranges=[]

>>>mangos=[]

>>> bananas=[]

>>> for fruit in alist:

        If fruit=="orange":

            oranges.append(fruit)

        elif fruit=="mango":

            mangos.append(fruit)

        elif fruit=="banana"

            bananas.append(fruit)

blist=[oranges,mangos,bananas]

There has to be an easier and cleaner way to do this, right?

1 Answers

One possible solution is to use collections.Counter:

from collections import Counter

blist = [[k] * v for k, v in Counter(alist).items()]
print(blist)

Prints:

[['orange', 'orange', 'orange'], ['mango', 'mango'], ['banana']]

Or:

blist = {}
for v in alist:
    blist.setdefault(v, []).append(v)
blist = list(blist.values())

print(blist)
Related