Python 如何使用循环给列表中的变量赋值
在这篇文章中,我们将讨论在Python中使用循环为列表中的变量赋值的不同方法。
使用简单的循环迭代
在这种方法中,我们使用for循环将元素添加到列表中。当我们不输入任何元素进入列表并停止添加时,我们只需按下回车键。
要将元素追加到列表中,我们使用 append() 方法。
示例1
以下是使用循环在Python中使用append()方法为列表中的变量赋值的示例。
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
以下是一个使用循环在Python中使用 globals() 方法为列表中的变量赋值的示例。
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