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

发布于 2025-01-10 03:43:29 字数 349 浏览 0 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

千笙结 2025-01-17 03:43:29

在 Python 中,变量在内部存储在字典。通过这些字典,您可以通过将变量名称作为字符串来访问和删除变量。示例:

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

使用 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:

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.

我很OK 2025-01-17 03:43:29

仍然不确定您的用例是什么,但字典可能很合适:

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

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

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())
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文