你可以在索引2.使用itertools.groupby
到组基于价值的元组然后为每个组可以使用random.choice
选择一个元组:
>>> from itertools import groupby
>>> import random
>>> l = [(0, 4, 1.0), (1, 4, 1.0), (3, 4, 1.0), (0, 3, 2.0), (1, 3, 2.0), (0, 2, 3.0), (1, 2, 3.0), (2, 4, 4.0), (2, 3, 5.0), (0, 1, float('inf'))]
>>> [random.choice(tuple(g)) for _, g in groupby(l, key=lambda x: x[2])]
[(1, 4, 1.0), (1, 3, 2.0), (1, 2, 3.0), (2, 4, 4.0), (2, 3, 5.0), (0, 1, inf)]
在上面groupby
回报可迭代(key, group)
元组,其中关键是值通过第二个参数返回给groupby
和组是可迭代的元素的组内:
>>> [(k, tuple(g)) for k, g in groupby(l, key=lambda x: x[2])]
[(1.0, ((0, 4, 1.0), (1, 4, 1.0), (3, 4, 1.0))), (2.0, ((0, 3, 2.0), (1, 3, 2.0))), (3.0, ((0, 2, 3.0), (1, 2, 3.0))), (4.0, ((2, 4, 4.0),)), (5.0, ((2, 3, 5.0),)), (inf, ((0, 1, inf),))]
因为我们不需要的关键,我们可以放弃它并转换组到序列random.choice
预计:
>>> [random.choice(tuple(g)) for _, g in groupby(l, key=lambda x: x[2])]
[(1, 4, 1.0), (1, 3, 2.0), (0, 2, 3.0), (2, 4, 4.0), (2, 3, 5.0), (0, 1, inf)]
注意,上述预期与相同值元组索引2是在输入彼此相邻。如果不是这种情况,您可以在将原始列表传递到groupby
之前对其进行排序。
更新如果你只是想要的结果,你可以用它代替列表理解发电机表达,并从那里获取值出与islice
的三个第一值:
>>> from itertools import islice
>>> gen = (random.choice(tuple(g)) for _, g in groupby(l, key=lambda x: x[2]))
>>> list(islice(gen, 3))
[(0, 4, 1.0), (1, 3, 2.0), (0, 2, 3.0)]
都与相同的值索引2元组在输入中彼此相邻?如果不是输出的正确顺序是什么? – niemmi
我可以对它们进行排序,就像它们高于 –