作者cococrisp7 (LIVEBA)
看板Python
標題[問題] list與dict的混用
時間Wed Jul 22 20:56:56 2020
大家好, 小弟目前在正在做爬蟲程式, 遇到了一個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
推 papple23g: countries.append(country_dict[country_input]) 07/22 21:39
推 OnoderaHaru: print([country_dict[country] for country in 07/22 21:40
→ OnoderaHaru: countries]) 07/22 21:40
→ refusekkk: 2F正解 1F應該是沒看到爬蟲網址會搭配用到us, de 07/23 10:23