遍历列表时打印变量名称

时间:2019-05-28 14:34:11

标签: python

考虑变量列表和Python列表:

apple='green'
banana='yellow'
orange='orange'

fruits = [apple, banana, orange]

当悬停在列表元素上时,如何打印变量名称而不是其值?

for fruit in fruits:
    #print the names of variables, that is "apple", "banana", etc.

我知道字典更适合解决这个问题,但是出于争论的目的,是否可以用列表来完成它?

3 个答案:

答案 0 :(得分:-1)

这有点作弊,但是如果将变量的名称存储在fruits数组中,而不是将变量本身存储在变量中,那将是微不足道的:

>>> apple = 'green'
>>> banana = 'yellow'
>>> orange = 'orange'
>>> fruits = ['apple','banana','orange']
>>> for fruit in fruits:
...     print fruit, vars()[fruit]
...     
apple green
banana yellow
orange orange

如果您真的想要获取变量名,则可能会遇到问题,因为数组未存储变量,而是存储了它指向的字符串-例如,您可以在赋值后更改apple的内容以演示数组包含原始字符串:

>>> fruity = [ apple, orange, banana ]
>>> apple = 'yikes'
>>> print fruity
['green', 'orange', 'yellow']

您能做的最好的事情是对vars()字典进行反向查找,然后尝试查找变量...

>>> yy = dict([v,k] for k,v in vars().items() if isinstance(v,str))
>>> for fruit in fruity:
...     print yy.get(fruit,'Unknown'), fruit
...     
Unknown green
orange orange
banana yellow

答案 1 :(得分:-1)

您想要这个:

apple = "green"
banana = "yellow"
orange = "orange"

fruits = [apple, banana, orange]
for fruit in fruits:
    fruit_name = [key for key, value in locals().items() if value == fruit]
    print(fruit_name[0])

答案 2 :(得分:-2)

使用NamedObject,它应该起作用:

apple='green'
banana='yellow'
orange='orange'
fruits = [apple, banana, orange]    

apple = NamedObject('apple', apple)
print(apple)
print(apple.name)

这应该打印:

green
apple

如果您不理解,这是另一件事:Access the name of a list in a Python print statement