使用循环将值分配给列表中的变量 [英] Assigning values to variables in a list using a loop
问题描述
var_list = [one, two, three]
num = 1
for var in var_list:
var = num
num += 1
以上内容给我一个错误,提示一个"不存在.不能以这种方式分配吗?我想为列表中的每个var分配一个递增的数字.
The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an incrementing number for each var in the list.
推荐答案
Python变量是值的名称.它们并没有真正包含"这些值.
Python variables are names for values. They don't really "contain" the values.
for var in var_list:
依次使"var"成为列表中每个元素的名称.在循环内部,var = num
不会影响列表:相反,它会导致var
不再是list元素的名称,而是开始成为任何num
当前名称的名称.
for var in var_list:
causes 'var' to become a name for each element of the list, in turn. Inside the loop, var = num
does not affect the list: instead, it causes var
to cease to be a name for the list element, and instead start being a name for whatever num
currently names.
类似地,当您创建列表时,如果one
,two
和three
还不是值的名称,则不能那样使用它们,因为您要创建一个列表.具有这些名称的值(然后使var_list
为该列表的名称).请注意,该列表实际上也没有包含任何值:它引用(即共享它们).
Similarly, when you create the list, if one
, two
and three
aren't already names for values, then you can't use them like that, because you are asking to create a list of the values that have those names (and then cause var_list
to be a name for that list). Note that the list doesn't really contain the values, either: it references, i.e. shares them.
这篇关于使用循环将值分配给列表中的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!