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

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

發(fā)展一個(gè) for 循環(huán)以跳過不等于的字典鍵和值

發(fā)展一個(gè) for 循環(huán)以跳過不等于的字典鍵和值

嗶嗶one 2023-05-09 10:42:49
背景我的結(jié)構(gòu)如下: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']},]如您所見,大多數(shù)鍵是'href',大多數(shù)值包含'https://www.simplyrecipes.com/recipes/'. 問題是那些不符合此命名約定的鍵和值......代碼:此代碼遍歷結(jié)構(gòu)并使用re.findall獲取之間的字符串值'recipes/',然后繼續(xù)/為其對應(yīng)的值創(chuàng)建一個(gè)新的鍵名。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})輸出:假設(shè)我刪除了不符合被命名和包含代碼字符串值的命名約定的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如果結(jié)構(gòu)的鍵和值不符合代碼中的命名約定,我會得到一個(gè)。問題:我將如何改進(jìn)這段代碼,以便它跳過任何未命名的鍵'href',如果它們被命名'href',如果它們的值不包含,將跳過'https://www.simplyrecipes.com/recipes/'?
查看完整描述

1 回答

?
森林海

TA貢獻(xiàn)2011條經(jīng)驗(yàn) 獲得超2個(gè)贊

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如果他們不滿足。


查看完整回答
反對 回復(fù) 2023-05-09
  • 1 回答
  • 0 關(guān)注
  • 148 瀏覽
慕課專欄
更多

添加回答

舉報(bào)

0/150
提交
取消
微信客服

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

幫助反饋 APP下載

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

公眾號

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