2016-07-29 34 views
1
class SpreadsheetRow(object): 
def __init__(self,Account1): 
    self.Account1=Account1 
    self.Account2=0 

我有一個while循環填充對象列表,另一個循環填充關聯Var1:Account2的字典。但是,如果密鑰與對象的Account1匹配,我需要將該字典的值存入每個對象。如何將dict鍵與列表中的對象的屬性相關聯?

所以基本上,我有:

listofSpreadsheetRowObjects=[SpreadsheetRow1, SpreadsheetRow2, SpreadsheetRow3] 
dict_var1_to_account2={1234:888, 1991:646, 90802:5443} 

我已經試過這樣:

for k, v in dict_var1_to_account2.iteritems(): 
    if k in listOfSpreadsheetRowObjects: 
     if self.account1=k: 
       self.account2=v 

但是,它不工作,我懷疑這是我的第一個 「如果」 語句,因爲listOfSpreadsheetRowObjects是隻是這些對象的列表。我如何訪問每個對象的account1,以便根據需要匹配它們?

最後,我應該有以下信息三個對象: SpreadsheetRow self.Account1 =帳戶1 self.Account2 =(V從我的字典裏,如果帳戶1在我的字典中的密鑰相匹配)

+0

您需要CL arify你的變量是什麼,'Account1value'是什麼?它應該是來自參數的「Account1」嗎?什麼是「SpreadsheetRow1」,「SpreadsheetRow2」等?他們是否是SpreadsheetRow的實例,通常以大寫字母開頭的名稱都是類。 –

+0

編輯,希望更清楚 – user3097421

+0

好,因爲它是一個字典,我期望'self.Account2 = dict_of_account1_to_account2 [self.Account1]'但我不明白你在哪裏把代碼,爲什麼它檢查'如果k在listOfSpreadsheetRowObjects:'那永遠不會實現... –

回答

0

你可以使用內any()生成器表達式來檢查是否有任何account1這些對象的屬性等於與k

if any(k == item.account1 for item in listOfSpreadsheetRows): 
+0

「:」k == item.account1 – galaxyan

+0

@galaxyan是的,感謝評論;-) – Kasramvd

+0

編輯:我是。知道了,謝謝! – user3097421

0

你可以嘗試使用next函數這樣:

next(i for i in listOfSpreadsheetRows if k == i.account1) 
0

如果你有一本字典d並希望得到相關的關鍵x則查找該值這樣的值:

v = d[x] 

所以,如果你的字典被稱爲dict_of_account1_to_account2和關鍵是self.Account1並希望該值設置爲self.Account2,那麼你會怎麼做:

self.Account2 = dict_of_account1_to_account2[self.Account1] 

使用字典的重點在於,你不必遍歷整個事物來查找事物。

否則,如果你正在創建的所有SpreadsheetRow對象,然後使用self無厘頭後做的.Account2這個初始化,您將需要通過每個SpreadsheetRow項目迭代,併爲每一個做作業,這樣的事情:

for row in listofSpreadsheetRowObjects: 
    for k, v in dict_of_account1_to_account2.iteritems(): 
     if row.Account1 == k: 
      row.Account2 = v 

但同樣,你不必遍歷字典來進行分配,剛剛從字典查找row.Account1

for row in listofSpreadsheetRowObjects: 
    row.Account2 = dict_of_account1_to_account2[row.Account1] 
+0

for row of listofSpreadsheetRowObjects: row.Account2 = dict_of_account1_to_account2 [row.Account1]給了我一個KeyError .... – user3097421

+0

好吧,所以我覺得混亂的是我的變量名。我已經改變他們希望顯示我在做什麼。 – user3097421

相關問題