擅长:python、mysql、java
<p>免责声明:“使用列表理解”的要求是荒谬的。</p>
<p>此外,如果您想使用权重,在Eli Bendersky的<a href="http://eli.thegreenplace.net/2010/01/22/weighted-random-generation-in-python/" rel="noreferrer">weighted random sampling</a>页面上列出了许多优秀的方法。</p>
<p>以下是低效,不可扩展等</p>
<p>也就是说,它不是一个而是两个(两个!)列表理解,返回列表,从不重复元素,并在某种意义上尊重权重:</p>
<pre><code>>>> 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]
</code></pre>
<p>。。或者,按照FMc的简化:</p>
<pre><code>>>> [x for x in random.choice([p for p in itertools.permutations(s, 3) if len(set(p)) == 3])]
[3, 5, 2]
</code></pre>
<p>(我将把<code>x for x</code>放在那里,即使不简单地写<code>list(random.choice(..))</code>或仅仅把它作为元组..)</p>