简体   繁体   English

(Python)元组/列表分配

[英](Python) Tuple/List Assignment

Currently to assign my variables, I have this: 目前要分配我的变量,我有这个:

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]

This creates 5 rows with random values: 这将创建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')

I would like to reassign the "X"s to numbers so it reads something like: 我想将“ 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')

However, when I use this: (example only - the location is user-determined) 但是,当我使用此命令时:(仅作为示例-位置由用户确定)

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

Is there something I can do to fix this so that I can change the values without the error? 我可以做些什么来解决此问题,以便我可以更改值而不会出现错误? Thanks. 谢谢。

You are creating a list with tuples: 您正在使用元组创建列表:

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

You can make those lists instead: 您可以改为列出这些列表:

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

Note the square brackets as opposed to the round parenthesis there. 注意方括号,而不是那里的圆括号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM