I want to separate a list of objects into sublists, where objects with same attribute/characteristic stay in the same sublist.
Suppose we have a list of strings:
["This", "is", "a", "sentence", "of", "seven", "words"]
We want to separate the strings based on their length as follows:
[['sentence'], ['a'], ['is', 'of'], ['This'], ['seven', 'words']]
The program I currently come up with is this
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?
With defaultdict(list)
, you can omit the key-existence check:
from collections import defaultdict
word_len_dict = defaultdict(list)
for word in sentence:
word_len_dict[len(word)].append(word)
Take a look at itertools.groupby()
. Note your list must be sorted first (more expensive than your method OP).
>>> from itertools import groupby
>>> l = ["This", "is", "a", "sentence", "of", "seven", "words"]
>>> print [list(g[1]) for g in groupby(sorted(l, key=len), len)]
[['a'], ['is', 'of'], ['This'], ['seven', 'words'], ['sentence']]
or if you want a dictionary ->
>>> {k:list(g) for k, g in groupby(sorted(l, key=len), len)}
{8: ['sentence'], 1: ['a'], 2: ['is', 'of'], 4: ['This'], 5: ['seven', 'words']}
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