第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅在循環(huán)中第一次修改可能的重復元素

僅在循環(huán)中第一次修改可能的重復元素

慕慕森 2021-11-16 15:15:45
我有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)


查看完整回答
反對 回復 2021-11-16
?
躍然一笑

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)


查看完整回答
反對 回復 2021-11-16
  • 2 回答
  • 0 關注
  • 153 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網(wǎng)微信公眾號