制作变量列表(或可迭代)引用变量 [Python]
Python(最好是3.6+)中有没有一种方法可以创建一个由变量组成的列表来引用变量本身,而不是它们的值?
举个例子:
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']
这可能吗?我正在使用 python 3.8。
回应评论:任何可迭代都是可以接受的。实际上,我有一个类似的问题,关于如何删除名称为字符串的变量,但这是另一个问题的主题。但这确实与此有关,所以我决定检查一下是否可能。
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?
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.
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在 Python 中,变量在内部存储在字典。通过这些字典,您可以通过将变量名称作为字符串来访问和删除变量。示例:
使用
globals()
表示全局变量,使用locals()
表示局部变量,使用object.__dict__
表示对象成员。In Python, variables are internally stored in dictionary. Through these dictionaries, you can access and delete variables by giving their names as strings. Example:
Use
globals()
for global variables,locals()
for local variables orobject.__dict__
for object members.仍然不确定您的用例是什么,但字典可能很合适:
Still not sure what your use case is, but a dictionary might be a good fit: