如何从元组列表的一部分中提取随机元素



我有一个元组列表,如下所示:

[(6, 1), (7, 1), (1, 2), (3, 2), (5, 2), (2, 4), (4, 4)]

我已经根据第二个元素对它进行了排序,如果你看到前两个元组,(6,1(和(7,1(都有1,我想从共有第二个单元并且在第一个位置的元组中选择一个随机元组,所以在这种情况下,在第二个位置有1的元组。

您可以使用itertools.groupby():

>>> import random
>>> import itertools
>>> l = [(6, 1), (7, 1), (1, 2), (3, 2), (5, 2), (2, 4), (4, 4)]
>>> for item in itertools.groupby(l, lambda k: k[1]):
...     print(random.choice(list(item[1])))
...
(6, 1)
(5, 2)
(4, 4)

这假设列表已排序(如您的问题所述(。

如果你只想要第一个元素,你可以使用

random.choice(list(next(itertools.groupby(l, lambda k: k[1]))[1]))

(事实上,这很难阅读,所以我将对其进行分解:(

random.choice(  # select a random item
list(          # from the list of results
next(         # of the first group
itertools.groupby(l, lambda k: k[1]) # grouped by the second number in the tuple
)
[1]           # use the second element of that list (the first is the key)
)

尽管问题已经得到了回答,但这里有一个不使用itertools的解决方案:

import random
L = [(6, 1), (7, 1), (1, 2), (3, 2), (5, 2), (2, 4), (4, 4)]
G = list(set([ x[1] for x in L ]))
for g in G:
l = [ x for x in L if x[1] == g ]
print (l[random.randint(0,len(l)-1)])

输出:

(7, 1)
(1, 2)
(4, 4)

最新更新