Python:如何打印动态变量

时间:2017-01-29 06:39:19

标签: python

我来自PHP背景,我正在尝试打印每次迭代。我无法理解如何在Python中实现它

>>> a0, a1, a2 = [12, 5, 8]
>>> b0, b1, b2 = [5, 9, 11]
>>> categories = [0, 1, 2]
>>> for i in categories:
        print(a+i)

错误:

Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'a' is not defined
>>> for i in categories:
...    print('a'+i)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
TypeError: cannot concatenate 'str' and 'int' objects
>>> for i in categories:
...     print(a+str(i))
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
NameError: name 'a' is not defined

我知道这是基本的,但我不知道如何解决它。

修改

>>> print a0
12
>>> print a2
8

a0,a1,a2是可变的。因为我有0,1,2 in,所以我不需要手动写a0,a1,a2,b0,b1,b2。

2 个答案:

答案 0 :(得分:1)

我认为你不会在python中这样做。更多pythonic将值存储为列表或数组,如:

a = [1, 2, 3]
cat = [0, 1, 2]
for i in cat:
    print(a[i])

答案 1 :(得分:-4)

>>> a0, a1, a2 = [12, 5, 8]
>>> b0, b1, b2 = [5, 9, 11]
>>> categories = [0, 1, 2]

for i in categories:        
    print(eval('a'+str(i)))

eval会将字符串变为变量, 打印变量a0,a1,a2

也是如此
output :
12
5
8