2023-11-08|閱讀時間 ‧ 約 2 分鐘

Python Dictionary ,set

字典中的候選人居住地排列沒有按照字母排,且有重複,想印出候選人居住地並依字母順序排列

candidates=[
{"Name":"Lai","Party":"DPP","Born":"New Taipei" },
{"Name":"Hou","Party":"KMT","Born":"Chiayi"},
{"Name":"Ko","Party":"TPP","Born":"Hsinchu"},
{"Name":"Guo","Party":None,"Born":"New Taipei"}
]

born=[]
for i in candidates:
# Put candidates Name in name[]
if i["Born"] not in born:
name.append(i["Born"])

for i in sorted(born):
print(i)

Terminal 印出​
Chiayi
Hsinchu
New Taipei
-------------------------------------------
candidates=[
{"Name":"Lai","Party":"DPP","Born":"New Taipei" },
{"Name":"Hou","Party":"KMT","Born":"Chiayi"},
{"Name":"Ko","Party":"TPP","Born":"Hsinchu"},
{"Name":"Guo","Party":None,"Born":"New Taipei"}
]
#用set()
born=set()
for i in candidates:
born.add(i["Born"])
for i in sorted(born):
print(i)

Terminal 印出​
Chiayi
Hsinchu
New Taipei
分享至
成為作者繼續創作的動力吧!
小妹愛玩空拍機,也在練習寫程式,把寫過的程式放上來。
從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

發表回應

成為會員 後即可發表留言
© 2024 vocus All rights reserved.