使用循环为列表中的变量赋值 [英] Assigning values to variables in a list using a loop

查看:44
本文介绍了使用循环为列表中的变量赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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. So I want the equivalent of

one = 1
two = 2
three = 3

但无需手动创建和初始化所有变量.我该怎么做?

but without having to manually create and initialize all variables. How can I do this?

推荐答案

Python 变量是值的名称.它们并不真正包含"这些值.

Python variables are names for values. They don't really "contain" the values.

for var in var_list: 依次使var"成为列表中每个元素的名称.在循环内部,var = num 不影响列表:相反,它导致 var 不再是列表元素的名称,而是开始成为列表元素的名称任何 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.

同样,当您创建列表时,如果 onetwothree 还不是值的名称,那么您可以不要像这样使用它们,因为您要求创建具有这些名称的值的列表(然后使 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆