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']]
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())]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With