简体   繁体   English

制作变量列表(或可迭代的)引用变量[Python]

[英]Making a list (or iterable) of variables refer to the variables [Python]

Is there a way in Python (preferably 3.6 +) to make a list made from variables to refer the variables themselves, and not their values? Python(最好是 3.6 +)有没有办法制作一个由变量组成的列表来引用变量本身,而不是它们的值?

An example:一个例子:

a, b, c = 1, 2, 3
l = [a, b, c]
print(l)
# Outputs: [1, 2, 3]
# I want: [a, b, c]
# Not preferred but acceptable: ['a', 'b', 'c']

Is this even possible?这可能吗? I'm using python 3.8.我正在使用 python 3.8。

In response to the comments: Any iterable is acceptable.回应评论:任何可迭代的都是可以接受的。 I actually have a similar question on how to delete a variable given it's name as a string, but that's a topic for another question.我实际上有一个类似的问题,关于如何删除一个变量,因为它的名称是一个字符串,但这是另一个问题的主题。 This does relate to that though, so I decided to check if it was possible.不过,这确实与此有关,所以我决定检查一下是否可行。

In Python, variables are internally stored in dictionary .在 Python 中,变量内部存储在字典中 Through these dictionaries, you can access and delete variables by giving their names as strings.通过这些字典,您可以通过将变量的名称作为字符串来访问和删除变量。 Example:例子:

a, b, c = 1, 2, 3
names = ['a', 'b', 'c']

for name in names:
    print(globals()[name])

print(a)
del globals()['a']
print(a) # a has been removed

Use globals() for global variables, locals() for local variables or object.__dict__ for object members.对全局变量使用globals() ,对局部变量使用locals() ,对 object 成员使用object.__dict__

Still not sure what your use case is, but a dictionary might be a good fit:仍然不确定您的用例是什么,但字典可能很合适:

d = {'a': 1, 'b': 2, 'c': 3}

l = ['a', 'b', 'c']
# or 
# l = list(d.keys())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM