Python列表类型列表连接,随机模块

时间:2016-06-20 16:57:52

标签: python python-3.x

我想要实现的目标:n个硬币翻转的可用组合列表

我运行此代码时得到的结果:包含来自2个可能结果的字母的列表" head"和"尾巴" 。为什么?我想不出来。

def randomlist(n):
l = []
for i in range(n):
    a = random.randint(1,2)
    if a == 1:
        l[len(l):] = ("heads")
    else:
        l[len(l):] = ("tails")
return l


listy = randomlist(20)

print(listy)

3 个答案:

答案 0 :(得分:2)

尝试使用append代替切片分配。

def randomlist(n):

    l = []
    for i in range(n):
        a = random.randint(1,2)
        if a == 1:
            l.append("heads")
        else:
            l.append("tails")
    return l

答案 1 :(得分:0)

要生成n硬币翻转的随机列表,您还可以使用list comprehension以更简洁的方式表达相同的逻辑:

>>> import random
>>> 
>>> def randomlist(n):
...     return ["heads" if random.randint(0, 1) else "tails"
...             for _ in range(n)]
... 
>>> randomlist(10)
['tails', 'tails', 'tails', 'tails', 'heads', 'heads', 'heads', 'tails', 'tails', 'heads']
>>> randomlist(6)
['heads', 'tails', 'heads', 'heads', 'heads', 'heads']

在上面的代码中,生成随机整数0或1(而不是1或2),以便在"heads""tails"之间进行判断时使用它们 - 使用0求值为{的事实{1}},以及1到False

现在,如果您的目的是生成所有可能的结果,即翻转硬币True次,您可以使用itertools.productn的示例(最终输出缩短了可读性):

n=3

答案 2 :(得分:0)

您也可以使用itertools库。它变得非常简单。

>>> from itertools import product
>>> product(['heads','tails'], repeat=3) # change the repeat parameter to set the length 
<itertools.product object at 0x0000000003B715A0>
>>> import random
>>> list(_)[random.randint(0,len(_))] # get a random sequence
('heads', 'tails', 'heads')

如果您需要快速生成大量序列,这会派上用场。只需将product结果保存在变量中,然后从中检索随机索引。