我正在 python 2.7 中创建一个列表 该列表由 1 和 0 组成,但是我需要 1 在列表中随机出现并指定一定的次数。
这是我发现的一种方法,但是创建列表可能需要很长时间
numcor = 0
while numcor != (wordlen): #wordlen being the set amount of times
usewrong = []
for l in list(mymap):
if l == "L": #L is my map an telling how long the list needs to be
use = random.choice((True, False))
if use == True:
usewrong.append(0)
else:
usewrong.append(1)
numcor = numcor + 1
有更有效的方法吗?
最佳答案
使用 0
和“1”创建列表的更简单方法是:
>>> n, m = 5, 10
>>> [0]*n + [1]*m
[0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
其中 n
是 0
的数量,m
是 1
的数量
但是,如果您希望列表按随机顺序洗牌,您可以使用 random.shuffle()
如:
>>> from random import shuffle
>>> mylist = [0]*n + [1]*m # n and m are from above example
>>> shuffle(mylist)
>>> mylist
[1, 1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 1, 1]
关于python - 创建一个列表,其中某个字符出现一定次数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39611916/