[問題] list與dict的混用

看板Python作者 (LIVEBA)時間5年前 (2020/07/22 20:56), 編輯推噓2(202)
留言4則, 3人參與, 5年前最新討論串1/1
大家好, 小弟目前在正在做爬蟲程式, 遇到了一個lis與dict互用的問題, 擷取程式的其 中 countries = [] country_dict = {'us':'United States', 'de':'Germany', 'fr':'France', 'jp':'Jap an', 'es':'Spain', 'gb':'Great} while True: country_input = input('Please enter the countries (or type q to exit) : if country_input == 'q': break elif country_input in list(country_dict.keys()): countries.append(country_input) elif country_input not in list(country_dict.keys()): print('Country Not Found, please retry again !!') print(countries) 假如輸入 us, de => 會印出['us', 'de'] 如果想要輸出對應到country_dict的value 讓輸出變成['United States', 'Germany'], 應該要怎麼修改呢? countries=[] 這個list需要保留,因為之後的爬蟲網址會搭配用到us, de這些縮寫來做 迴圈 想了很久還是想不出來, 希望有人可以指點一下~感謝! -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.52.199.191 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1595422618.A.0EA.html

07/22 21:39, 5年前 , 1F
countries.append(country_dict[country_input])
07/22 21:39, 1F

07/22 21:40, 5年前 , 2F
print([country_dict[country] for country in
07/22 21:40, 2F

07/22 21:40, 5年前 , 3F
countries])
07/22 21:40, 3F

07/23 10:23, 5年前 , 4F
2F正解 1F應該是沒看到爬蟲網址會搭配用到us, de
07/23 10:23, 4F
文章代碼(AID): #1V63UQ3g (Python)
文章代碼(AID): #1V63UQ3g (Python)