免责声明:“使用列表理解”的要求是荒谬的。
此外,如果您想使用权重,Eli Bendersky 的页面上列出了许多优秀的方法加权随机抽样 http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/.
以下是效率低下、无法扩展等。
也就是说,它不是一个而是两个(两个!)列表推导式,返回一个列表,从不重复元素,并且在某种意义上尊重权重:
>>> s = [1, 2, 1, 4, 5, 2, 3, 2, 4, 5, 3, 1, 4, 2]
>>> [x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]
[3, 1, 2]
>>> [x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]
[5, 3, 4]
>>> [x for x in random.choice([p for c in itertools.combinations(s, 3) for p in itertools.permutations(c) if len(set(c)) == 3])]
[1, 5, 2]
.. 或者,如 FMc 所简化:
>>> [x for x in random.choice([p for p in itertools.permutations(s, 3) if len(set(p)) == 3])]
[3, 5, 2]
(我将离开x for x
在那里,尽管不简单地写会很痛苦list(random.choice(..))
或者只是将其保留为元组..)