Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to combine strings in a list that have same length and create lists of list in python

Tags:

python

I have a list of strings. Based on the length of each string, I need to group them in one list. finally one list should contain all the lists.

Example:

input

in=['the', 'way', 'you', 'see', 'people', 'is', 'the', 'way', 'you', 'treat', 'them', 'and', 'the', 'way', 'you', 'treat', 'them', 'is', 'what', 'they', 'become']

output

expected_out=[['is'],['and', 'see', 'the', 'way', 'you'], ['them', 'they', 'what'], ['treat'], ['become', 'people']]
like image 242
user6054437 Avatar asked Jan 02 '26 03:01

user6054437


1 Answers

Don't know if this is the best way to do it, but it's the first thing that came to my mind:

from collections import defaultdict

len2words = defaultdict(set)

for word in input_list:
    len2words[len(word)].add(word)

output = [list(len2words[key]) for key in sorted(len2words.keys())]
like image 55
L3viathan Avatar answered Jan 03 '26 16:01

L3viathan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!