Python list of lists depending on length

Viewed 513

I have the lists below and I need to assign the strings from fruit list into stall list depending on their length.

fruit = ['an', 'king', 'be', 'brave']
stall = [[],[],[],[]]

So the result should be like this

stall = [[ ],['an', 'be'],[ ],['king', 'brave']] 

I’ve tried so many ways and even attempted to create a new list to see where I am going wrong but not even this is populating anything. Can someone please point me where I am going wrong? I've never had to append to list of lists before.

i = 0
s = stall[i]
for j in fruit:
    if(len(j)) == i+1:
        s.append(j)
        i += 1
print(stall)
4 Answers

Assuming you want as many inner lists as you need to put in all words correctly:

fruit = ['an', 'king', 'be', 'brave']

stall = [
    [element for element in fruit if len(element) == i+1]
    for i in range(len(fruit) + 1)
]

stall will now be [[], ['an', 'be'], [], ['king'], ['brave']].

I'm not sure if classifying king and brave together, as your question does, was deliberate or not. I'm assuming deliberate.

fruit = ['an', 'king', 'be', 'brave']
stall = [[],[],[],[]]
for f in fruit:
        stall[min(len(f),4)-1].append(f)

This will give you

>>> stall
[[], ['an', 'be'], [], ['king', 'brave']]

A simple O(n) approach:

fruit = ['an', 'king', 'be', 'brave']

lookup = {}
for word in fruit:
    lookup.setdefault(len(word), []).append(word)

stall = [lookup.get(i, []) for i in range(1, max(lookup) + 1)]

print(stall)

An alternative using using defaultdict:

from collections import defaultdict

fruit = ['an', 'king', 'be', 'brave']

lookup = defaultdict(list)
for word in fruit:
    lookup[len(word)].append(word)

stall = [lookup.get(i, []) for i in range(1, max(lookup) + 1)]

print(stall)

Output

[[], ['an', 'be'], [], ['king'], ['brave']]

One way could be following. First you get the size of the empty list stall from the dimensions of the largest string in your fruit. Then you simply append the fruits to the corresponding position in your nested lists.

The len(f)-1 is used because the indexing in python starts from 0.

fruit = ['an', 'king', 'be', 'brave']
stall = [[] for _ in range(len(max(fruit, key=len)))]

for f in fruit:
    stall[len(f)-1].append(f)

print (stall)
# [[], ['an', 'be'], [], ['king'], ['brave']]
Related