亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

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

發展一個 for 循環以跳過不等于的字典鍵和值

發展一個 for 循環以跳過不等于的字典鍵和值

嗶嗶one 2023-05-09 10:42:49
背景我的結構如下:trash = [ {'href': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'},          {'href': 'https://www.simplyrecipes.com/recipes/cuisine/german/'},          {'href': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'},          {'href': 'https://www.simplyrecipes.com/recipes/type/condiment/'},          {'href': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}]          {'href': 'https://www.simplyrecipes.com/',           'title': 'Simply Recipes Food and Cooking Blog', 'rel': ['home']},]如您所見,大多數鍵是'href',大多數值包含'https://www.simplyrecipes.com/recipes/'. 問題是那些不符合此命名約定的鍵和值......代碼:此代碼遍歷結構并使用re.findall獲取之間的字符串值'recipes/',然后繼續/為其對應的值創建一個新的鍵名。for x in trash:    for y in x.values():        txt = ''        for i in re.findall("recipes/.*", y):            txt += i            title = txt.split('/')[1]            print({title: y})輸出:假設我刪除了不符合被命名和包含代碼字符串值的命名約定的keys和,如下所示:values'href''https://www.simplyrecipes.com/recipes/'{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/portuguese/'}{'cuisine': 'https://www.simplyrecipes.com/recipes/cuisine/german/'}{'season': 'https://www.simplyrecipes.com/recipes/season/seasonal_favorites_spring/'}{'type': 'https://www.simplyrecipes.com/recipes/type/condiment/'}{'ingredient': 'https://www.simplyrecipes.com/recipes/ingredient/adobado/'}問題:代碼的問題是,TypeError: expected string or bytes-like object如果結構的鍵和值不符合代碼中的命名約定,我會得到一個。問題:我將如何改進這段代碼,以便它跳過任何未命名的鍵'href',如果它們被命名'href',如果它們的值不包含,將跳過'https://www.simplyrecipes.com/recipes/'?
查看完整描述

1 回答

?
森林海

TA貢獻2011條經驗 獲得超2個贊

for d in trash:

    for key, value in d.items():

        if key != "href" or "https://www.simplyrecipes.com/recipes/" not in value:

            continue  # Move onto next iteration

        txt = ''

        for i in re.findall("recipes/.*", value):

            txt += i

            title = txt.split('/')[1]

            print({title: value})

您可以使用 迭代字典的鍵和值dict.items()。然后你可以使用if語句來檢查你的條件,continue如果他們不滿足。


查看完整回答
反對 回復 2023-05-09
  • 1 回答
  • 0 關注
  • 150 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號