如何在 Python 中使用循环为列表中的变量赋值?
本文将讨论在 Python 中使用循环为列表中的变量赋值的不同方法。
使用简单的循环迭代
在这种方法中,我们使用 for 循环将元素追加到列表中。当我们不再向列表中添加任何元素并停止追加时,只需按 Enter 键。
为了将元素追加到列表中,我们使用append()方法。
示例 1
以下是一个使用 append() 方法在 Python 中使用循环为列表中的变量赋值的示例。
L=[] while True: item=input("enter new item or press enter if you want to exit ") if item=='': break L.append(item) print ("List : ",L)
输出
执行以上代码后,将获得以下输出。
enter new item or press enter if you want to exit 5 enter new item or press enter if you want to exit 9 enter new item or press enter if you want to exit 6 enter new item or press enter if you want to exit List : ['5', '9', '6']
示例 2
在下面的示例中,变量名在 exec 语句中被引入 -
var_names = ['one','two','three'] count = 1 for n in var_names: exec ("%s = %s" % (n, count)) count +=1 print ('The values assigned to the variables are:',one, two, three)
输出
以下是上述代码的输出 -
The values assigned to the variables are: 1 2 3
使用 globals() 方法
在下面的示例中,我们使用globals()内置方法。您可以使用globals()方法访问全局变量的字典。
globals()方法检索当前全局符号表的字典。符号表是编译器维护的一种数据结构,其中包含程序所需的所有信息。
示例 3
以下是一个使用globals()方法在 Python 中使用循环为列表中的变量赋值的示例。
var_names = ["one", "two", "three"] count = 1 for name in var_names: globals()[name] = count count += 1 print(one) print(two) print(three)
输出
执行以上代码后,将获得以下输出。
1 2 3
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP