我有2張桌子。一個所有者可以沒有或多個項目。Itemid name owner_id (fk) 1 alpha 12 beta 1Ownerid name attrc 1 owner1 complex_attr12 owner2 complex_attr2 我從數(shù)據(jù)庫中分別檢索它們作為列表: for item in item_list: for owner in owner_list: if item.owner_id == owner.id: # I modify owner attributes owner.attrc = modify_funct(attrc) item.owner = owner 我名單Items中的HTML,并為每個Item我展示的一些屬性Owner的Item。在循環(huán)中,我創(chuàng)建Owner了Item對象的a 屬性;事情是在 html 中顯示我需要修改一些Owner原始數(shù)據(jù)庫屬性所以在 html 模板創(chuàng)建中,我會有類似的東西:for item in item_list: <div> item.name <span> item.owner.name<span> <span> item.owner.attrc<span></div>因為Owner with id 1擁有兩者Item with id 1 and 2,在循環(huán)中的第一次迭代中,attrc被修改,在循環(huán)中的第二次迭代中,'attrc' 已經被修改,并且該函數(shù)沒有找到預期的內容。解決方案是使用另一個循環(huán)循環(huán)/更改外部的“attrc”,然后循環(huán) item_list 和 owner_list,以減少循環(huán)次數(shù)?
2 回答

元芳怎么了
TA貢獻1798條經驗 獲得超7個贊
這不是最有效的解決方案,但它與您現(xiàn)有的代碼最相似:
for owner in owner_list:
if any(item.owner_id == owner.id for item in item_list):
owner.attrc = modify_funct(attrc)

躍然一笑
TA貢獻1826條經驗 獲得超6個贊
使用集合推導更有效的解決方案:
owner_ids = {item.owner_id for item in item_list}
for owner in owner_list:
if owner.id in owner_ids:
owner.attrc = modify_funct(attrc)
添加回答
舉報
0/150
提交
取消