gpt4 book ai didi

Python:如何按对象的特征或属性对对象列表进行分组?

转载 作者:太空狗 更新时间:2023-10-30 00:43:33 24 4
gpt4 key购买 nike

<分区>

我想将对象列表分成子列表,其中具有相同属性/特征的对象留在同一个子列表中。

假设我们有一个字符串列表:

["This", "is", "a", "sentence", "of", "seven", "words"]

我们希望根据字符串的长度分隔字符串,如下所示:

[['sentence'], ['a'], ['is', 'of'], ['This'], ['seven', 'words']]

我目前想出的程序是这样的

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()

我想知道是否有更好的方法来实现这一点?

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com