(Python)元组/列表分配

时间:2013-12-19 16:25:13

标签: python list python-3.x dictionary tuples

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

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

我有什么办法可以解决这个问题,以便我可以在没有错误的情况下更改值吗?感谢。

1 个答案:

答案 0 :(得分:5)

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

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]

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