gpt4 book ai didi

python - 创建一个列表,其中某个字符出现一定次数

转载 作者:行者123 更新时间:2023-12-01 03:41:14 25 4
gpt4 key购买 nike

我正在 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]

其中 n0 的数量,m1 的数量

但是,如果您希望列表按随机顺序洗牌,您可以使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com