2

我很惊讶我还没有找到没有循环的方法,因为这似乎是一个非常标准的问题。
在 python 中工作,我有 colors = ["red","green","blue"]并且我想将这些元素以随机顺序放入长度为 N 的列表中。现在我正在使用:

import random
colors = ["red","green","blue"]
otherList = []

for i in range (10):  # N=10 
    otherList.append(random.choice(colors))

这将返回:otherList = ["red","green","green","green","blue","green","red","green","green","blue"],这正是我想要的。我只是在寻找一种更惯用的方式来做到这一点?有任何想法吗?看起来 random.sample 可能是答案,但我在文档中没有看到任何完全符合我需求的内容。

4

2 回答 2

6

您可以使用列表推导:

[random.choice(colors) for i in range(10)] #xrange for python2 compatability

或者random.sample()通过一些体操:

nrandom = 10
random.sample( colors*(nrandom//len(colors)+1), nrandom )  

虽然我不认为这比列表理解更好......

于 2012-08-17T15:16:37.883 回答
2
>>> import random
>>> colors = ["red","green","blue"]
>>> [random.choice(colors) for i in range(10)]
['green', 'green', 'blue', 'red', 'red', 'red', 'green', 'red', 'green', 'blue']
于 2012-08-17T15:18:08.487 回答