如何解决Python:如何根据对象的特征或属性对对象列表进行分组?
看一看itertools.groupby()
。请注意,您的列表必须首先排序(比方法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']]
或者如果您想要 字典 ->
>>> {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']}
解决方法
我想将对象列表分成子列表,其中具有相同属性/特征的对象保留在同一子列表中。
假设我们有一个字符串列表:
["This","is","a","sentence","of","seven","words"]
我们要根据字符串的长度将它们分开,如下所示:
[['sentence'],['a'],['is','of'],['This'],['seven','words']]
我目前想出的程序是这样的
sentence = ["This","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()
我想知道是否有更好的方法来实现这一目标?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。