You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何打印数组元素对应的变量名而非值?

如何打印数组中元素对应的变量名?

当你执行以下代码时:

A = (2,0)
B = (3, 4)
C = (5, 6)
array1 = [A, B, C]

数组array1里存储的是坐标元组的值,而非变量名A、B、C——因为Python中变量名只是指向值的引用,存入数组的是引用指向的实际数据,所以直接打印只会输出坐标。

要实现打印变量名的需求,有两种常用方案:

方案1:使用字典存储名称与坐标的映射

用字典关联变量名(字符串形式)和对应的坐标,这样可以同时保留名称和值:

A = (2, 0)
B = (3, 4)
C = (5, 6)
point_dict = {'A': A, 'B': B, 'C': C}

# 打印单个变量名
print('A')
# 打印变量名对应的坐标
print(point_dict['A'])

# 遍历打印所有变量名和坐标
for name, coord in point_dict.items():
    print(f"{name}: {coord}")

方案2:自定义类封装名称与坐标

创建一个自定义类,把点的名称和坐标封装在一起,并重写__repr__方法来控制打印时的显示内容:

class Point:
    def __init__(self, name, x, y):
        self.name = name
        self.coord = (x, y)
    
    def __repr__(self):
        return self.name

# 创建带名称的点实例
A = Point('A', 2, 0)
B = Point('B', 3, 4)
C = Point('C', 5, 6)
array1 = [A, B, C]

# 打印单个元素或数组时,会显示变量名
print(array1[0])  # 输出: A
print(array1)     # 输出: [A, B, C]

# 如需获取坐标,可访问实例的coord属性
print(array1[0].coord)  # 输出: (2, 0)

内容的提问来源于stack exchange,提问作者CloudNguyen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 10:35:24