I want to highlight a list of objects in sublists, where objects with the same attributes / characteristics remain in the same sublist.
Suppose we have a list of strings:
["This", "is", "a", "sentence", "of", "seven", "words"]
We want to separate the lines based on their length as follows:
[['sentence'], ['a'], ['is', 'of'], ['This'], ['seven', 'words']]
The program that I just invented is
sentence = ["This", "is", "a", "sentence", "of", "seven", "words"]
word_len_dict = {}
for word in sentence:
if len(word) not in word_len_dict.keys():
word_len_dict[len(word)] = [word]
else:
word_len_dict[len(word)].append(word)
print word_len_dict.values()
I want to know if there is a better way to achieve this?
source
share