相关疑难解决方法(0)

itertools.groupby()没有正确分组

我有这些数据:

self.data = [(1, 1, 5.0),
             (1, 2, 3.0),
             (1, 3, 4.0),
             (2, 1, 4.0),
             (2, 2, 2.0)]
Run Code Online (Sandbox Code Playgroud)

当我运行此代码时:

for mid, group in itertools.groupby(self.data, key=operator.itemgetter(0)):
Run Code Online (Sandbox Code Playgroud)

因为list(group)我得到:

[(1, 1, 5.0),
 (1, 2, 3.0),
 (1, 3, 4.0)]
Run Code Online (Sandbox Code Playgroud)

这就是我想要的.

但是,如果我使用1而不是0

for mid, group in itertools.groupby(self.data, key=operator.itemgetter(1)):
Run Code Online (Sandbox Code Playgroud)

按元组中的第二个数字分组,我只得到:

[(1, 1, 5.0)]
Run Code Online (Sandbox Code Playgroud)

即使有其他元组在1(第二)位置有"1".

python python-itertools

11
推荐指数
2
解决办法
1万
查看次数

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

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

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

["This", "is", "a", "sentence", "of", "seven", "words"]
Run Code Online (Sandbox Code Playgroud)

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

[['sentence'], ['a'], ['is', 'of'], ['This'], ['seven', 'words']]
Run Code Online (Sandbox Code Playgroud)

我目前提出的计划是这样的

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()
Run Code Online (Sandbox Code Playgroud)

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

python arrays sorting algorithm

6
推荐指数
2
解决办法
7203
查看次数

标签 统计

python ×2

algorithm ×1

arrays ×1

python-itertools ×1

sorting ×1