簡體   English   中英

從字典中獲取值

[英]Getting values from a 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()

如果我理解您的問題正確,那么這是解決方案:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM