簡體   English   中英

如何將dict鍵與列表中對象的屬性相關聯?

[英]How can I associate a dict key to an attribute of an object within a list?

class SpreadsheetRow(object):
def __init__(self,Account1):
    self.Account1=Account1
    self.Account2=0

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

基本上,我有:

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

但是,它不起作用,我懷疑它是我的第一個“if”語句,因為listOfSpreadsheetRowObjects只是這些對象的列表。 我如何訪問每個對象的account1,以便根據需要匹配它們?

最后,我應該有三個對象,其中包含以下信息:SpreadsheetRow self.Account1 = Account1 self.Account2 =(v from my dictionary,如果account1與我字典中的鍵匹配)

您可以在any()使用生成器表達式來檢查這些對象的任何account1屬性是否與k相等:

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

您可以嘗試使用next函數:

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

如果您有一個字典d並希望獲得與鍵x相關聯的值,那么您可以像這樣查找該值:

v = d[x]

因此,如果你的字典被稱為dict_of_account1_to_account2並且密鑰是self.Account1並且你想將該值設置為self.Account2那么你會這樣做:

self.Account2 = dict_of_account1_to_account2[self.Account1]

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

否則,如果在創建所有SpreadsheetRow對象后對.Account2進行初始化,那么使用self是沒有意義的,您需要遍歷每個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]

暫無
暫無

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

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