从字典中获取值

时间:2013-11-25 07:43:57

标签: python class oop dictionary

以下是我正在使用的代码。我的程序创建了可能的位置组合并获得了最后的位置。然后我想根据列表A中的字母和字典字典VALUES获取该位置的值。当我执行此代码时,我得到:

AttributeError:'组合'对象没有属性'get_value'

X = ['A','B','C']  
Y = ['1','2','3']
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3}

class Combination:   # Creates a list of possible position combinations
    def __init__(self,x,y):
        if (x in X) and (y in Y):
            self.x = x
            self.y = y
        else:
            print "WRONG!!"

    def __repr__ (self):
        return self.x+self.y

class Position:     # Makes operation on the chosen position
    def __init__(self):
        self.xy = []
        for i in X:
            for j in Y:
                self.xy.append(Combination(i,j))

    def choose_last(self):
        return self.xy.pop()

    def get_value(self):
        return self.VALUES_FOR_X()

    def __str__(self):
        return "List contains: " + str(self.xy)

pos = Position()
print pos
last_item = pos.choose_last()
print "Last item is:", last_item
print  last_item.get_value()

有谁知道如何以最简单的方式更改此代码以使其正常工作?

该计划的逻辑: 我们有可能的X,Y位置。我们创造所有可能的组合。然后我们从可能的组合中选择最后一个位置,例如:C3 直到这里程序完美无缺 现在我想获得位置C3的值。在C3中使用'C'的字典值是3.我想打印这个值(3)。

为此,我添加了方法:

def get_value(self):
    return self.VALUES_FOR_X()

1 个答案:

答案 0 :(得分:1)

如果我理解你问题正确,这就是解决方案:

X = ['A','B','C']
Y = ['1','2','3']
VALUES_FOR_X = {'A':1, 'B': 2, 'C':3}

class Combination:   # Creates a list of possible position combinations
    def __init__(self,x,y):
        if (x in X) and (y in Y):
            self.x = x
            self.y = y
        else:
            print "WRONG!!"

    def get_value(self):
        return VALUES_FOR_X[self.x]

    def __repr__ (self):
        return self.x+self.y

class Position:     # Makes operation on the chosen position
    def __init__(self):
        self.xy = []
        for i in X:
            for j in Y:
                self.xy.append(Combination(i,j))

    def choose_last(self):
        return self.xy.pop()



    def __str__(self):
        return "List contains: " + str(self.xy)

pos = Position()
print pos
last_item = pos.choose_last()
print "Last item is:", last_item
print  last_item.get_value()

我的输出是:

>>>  List contains: [A1, A2, A3, B1, B2, B3, C1, C2, C3]  
>>>  Last item is: C3  
>>>  3