小编use*_*690的帖子

索引超出范围,但列表中有元素吗?

所以我一直在浏览这个网站试图解决我的问题,但我认为没有人有我的具体问题?我正在尝试做的是迭代并使用重复创建列表的排列.类似于我想要所有可能的结果滚动4面骰子3次.我不知道我的代码是否真的可以用于此目的,但手头的问题是这样的:

我有这个代码:

ops = ["add", "sub", "mul", "div"]    
def opsy():
    opslist=["cat", "dog", "cow"]
    for w in ops:
        opslist[0] = w
        for x in ops:
            opslist[1] = x
            for y in ops:
                opslist[2] = y
                opsarray.append(opslist)
Run Code Online (Sandbox Code Playgroud)

我收到这个错误:

IndexError: 'list assignment index out of range'
Run Code Online (Sandbox Code Playgroud)

我理解应该是因为opslist被定义为空列表,所以我改变了(如上面的代码所示),我仍然得到错误?另外我不认为" append"不是我想要的,我需要能够更改特定的索引,而不仅仅是添加项目.我也不想使用模块(itertools),我真的想自己编程.非常感谢.

编辑:我不知道为什么我有错误呢?但无论如何,马蒂诺的评论与opsarray = [[w, x, y] for y in ops for x in ops for w in ops]我想做的事情有关.是的 谢谢!

python indexing list

2
推荐指数
1
解决办法
128
查看次数

标签 统计

indexing ×1

list ×1

python ×1