【发布时间】:2022-01-04 08:59:48
【问题描述】:
我有一个我想传递给一些变量的名称列表,但是这些变量都有一个唯一的名称。我正在迭代,因为在这个例子中变量似乎很少,但在我的实际场景中,写出来并分配一个列表值会很多。
names = ["apple", 1, 50, "boat", 5, 90, "tree", 4, 96]
n1=q1=t1=""
n2=q2=t2=""
n3=q3=t3=""
name = 0
quantity = 1
total = 2
value = len(names)
value = (value // 3) + 1
for i in range(1, value):
tempN = "n" + str(i)
tempQ = "q" + str(i)
tempT = "t" + str(i)
# using locals(), when i print the variables, n1, q1, t1...they all end up empty .
# using exec() I get this error, all the examples to solve this error wasn't very helpful
# since most of them had to do with input from the user.
# File "<string>", line 1, in <module>
# NameError: name 'apple' is not defined
locals()[tempN] = names[name]
locals()[tempQ] = names[quantity]
locals()[tempT] = names[total]
exec("%s = %s" % (tempN, names[name]))
exec("%s = %s" % (tempQ, names[quantity]))
exec("%s = %s" % (tempT, names[total]))
name += 3
quantity += 3
total += 3
这有点过于简单化了,但想法保持不变,我有许多变量需要从列表中获取值。一切都可以改变,除了列表格式,或者它是一个列表的事实。
有没有人知道更好的方法或解决我的问题?
【问题讨论】: