在Python中检索列表对象的名称

时间:2017-04-22 22:36:23

标签: python

我有一个载体列表

vector1=[1,1]
vector2=[2,2]
favoritevector=[1,-1]

然后是那些载体的列表

vectors=[]
vectors.append(vector1)
vectors.append(vector2)
vectors.append(favoritevector)

vector
>>vector = [[1,1], [2,2], [1,-1]]

如何检索列表向量中的对象名称,而不是对象的实际值。

在这种情况下,我想要的是,如果我要求列表向量的元素0,则函数或命令将返回名称“vector1”而不是[1,-1]。

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

我认为有一种方法可以使用列表来完成此操作。您可以尝试这样的事情:

class vector(object):
    def __init__(self, name, x, y):
        self.name = name
        self.x = x
        self.y = y

    def __repr__(self):
        return """<vector {} {}>""".format(self.name, (self.x, self.y))

然后,你可以这样做:

vectors = []
vectors.append(vector(name="vector1", x=1, y=2))
vectors.append(vector(name="vector2", x=2, y=3))
# to get the name of the first vector, do:
vectors[0].name
# 'vector1'

答案 1 :(得分:0)

如果向量的顺序不重要,您可以使用词典

vectors_dict["vector1"] = [1, 1]