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

标签 python arrays list python-2.7

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

相关文章:

python - python中的Kruskels MST算法似乎不太正确

javascript - 基于动态标准的高效数组过滤

jQuery 将动态创建的列表放入 <ul> 标签内

android - 我想将 List<> 从 Activity A 传递到 B

python - 动态添加/删除线程到 celery 中的工作池

Python线程不会更改函数内的全局变量

python - 在 opencv 中使用均值合成帧

java - Foobar 错误 : Error compiling the code, 请稍后再试

python - 将数组列表转换为列表列表?

c++ - 子类化的 STL list<T>::reference 编译错误