嗯,这是一种在基本 Python 中执行此操作的方法:
In [90]: col1
Out[90]: [11, 11, 11, 11, 12, 12, 12]
In [91]: col2
Out[91]: [0.95, 0.75, 0.85, 0.65, 0.63, 0.75, 0.45]
In [92]: col3
Out[92]: [21, 22, 23, 24, 22, 24, 25]
让我们创建data,由每列中的项目组成:
在 [163] 中:数据 = [*zip(col1, col2, col3)]
In [164]: data
Out[164]:
[(11, 0.95, 21),
(11, 0.75, 22),
(11, 0.85, 23),
(11, 0.65, 24),
(12, 0.63, 22),
(12, 0.75, 24),
(12, 0.45, 25)]
让我们使用itertools 模块将它们分组:
In [174]: import itertools
In [175]: groups = itertools.groupby(data, key=lambda x: x[0])
现在,groups 是一个生成器。如果我们想看看它的样子
我们需要对其进行迭代:
for a, b, in groups:
print(a, list(b))
我们得到:
11 [(11, 0.95, 21), (11, 0.75, 22), (11, 0.85, 23), (11, 0.65, 24)]
12 [(12, 0.63, 22), (12, 0.75, 24), (12, 0.45, 25)]
但是我们用尽了迭代器。所以让我们再次创建它,现在
我们知道它包含什么,我们可以执行所需的排序:
In [177]: groups = itertools.groupby(data, key=lambda x: x[0])
In [178]: groups2 = [sorted(list(b), reverse=True) for a, b in groups]
In [179]: groups2
Out[179]:
[[(11, 0.95, 21), (11, 0.85, 23), (11, 0.75, 22), (11, 0.65, 24)],
[(12, 0.75, 24), (12, 0.63, 22), (12, 0.45, 25)]]
好的,还有一件事,我现在在编辑器中这样做:
for i in range(len(groups2)):
groups2[i] = [(x, i, z) for i, (x, y, z) in enumerate(groups2[i], 1)]
for g in groups2:
for item in g:
print(item)
我们得到:
(11, 1, 21)
(11, 2, 23)
(11, 3, 22)
(11, 4, 24)
(12, 1, 24)
(12, 2, 22)
(12, 3, 25)