Python列表类型列表串联、随机模块

标签 python python-3.x

我想要实现的目标:n 次抛硬币的可能组合列表

运行此代码时得到的结果:包含来自 2 个可能结果“正面”和“反面”的字母的列表。为什么?我想不通。

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)

最佳答案

尝试使用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

关于Python列表类型列表串联、随机模块,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37927976/

相关文章:

Python hashlib 没有为 md5 生成正确的哈希值

python - Pandas read_sql() - AttributeError : 'Engine' object has no attribute 'cursor'

python-3.x - 使用 shift() 比较行元素

python - 导入变量初始化

python - 执行用 yaml 编写的带有变量的 python 脚本

python - 如何使用 Python Regex 查找首字母大写的所有单词

python - 从模型 flask 、sqlalchamey 和 wtforms 创建表单

python - 音乐分析与可视化

python - 稠密矩形矩阵乘以稀疏矩阵

Python - 计算来自 txt 文件的标签的行之间的时间差