gpt4 book ai didi

python - (Python) 元组/列表赋值

转载 作者:太空宇宙 更新时间:2023-11-04 09:06:10 25 4
gpt4 key购买 nike

目前要分配我的变量,我有这个:

rows = [[convert[random.randint(0,7)] for _ in range(5)] for _ in range(5)]
printedrows = [("[X]","[X]","[X]","[X]","[X]"," <- V: {} TOTAL: {}".format(row.count(0), sum(row))) for row in rows]

这将创建具有随机值的 5 行:

('[X]', '[X]', '[X]', '[X]', '[X]', '  <- V: 1   TOTAL: 9') 
('[X]', '[X]', '[X]', '[X]', '[X]', ' <- V: 2 TOTAL: 5')
('[X]', '[X]', '[X]', '[X]', '[X]', ' <- V: 0 TOTAL: 6')
('[X]', '[X]', '[X]', '[X]', '[X]', ' <- V: 1 TOTAL: 10')
('[X]', '[X]', '[X]', '[X]', '[X]', ' <- V: 0 TOTAL: 8')

我想将“X”重新分配给数字,这样它的内容如下:

('[X]', '[2]', '[X]', '[X]', '[X]', '  <- V: 1   TOTAL: 9') 
('[1]', '[X]', '[3]', '[0]', '[1]', ' <- V: 2 TOTAL: 5')
('[X]', '[X]', '[1]', '[X]', '[X]', ' <- V: 0 TOTAL: 6')
('[1]', '[X]', '[X]', '[X]', '[2]', ' <- V: 1 TOTAL: 10')
('[X]', '[3]', '[X]', '[2]', '[X]', ' <- V: 0 TOTAL: 8')

但是,当我使用它时:(仅示例 - 位置由用户确定)

convert = {0:0,1:1,2:2,3:3,4:0,5:1,6:2,7:1}

printedrows[y][x] = rows[y][x]
TypeError: 'tuple' object does not support item assignment

我能做些什么来解决这个问题,这样我就可以在不出错的情况下更改值吗?谢谢。

最佳答案

您正在创建一个包含元组的列表:

printedrows = [("[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}".format(row.count(0), sum(row))) 
for row in rows]

您可以改为制作这些列表:

printedrows = [["[X]","[X]","[X]","[X]","[X]","  <- V: {}   TOTAL: {}".format(row.count(0), sum(row))] 
for row in rows]

请注意方括号而不是圆括号。

关于python - (Python) 元组/列表赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20686723/

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