Python Dictionary ,set

更新於 發佈於 閱讀時間約 3 分鐘

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

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
avatar-img
3會員
26內容數
寫程式的筆記,把一些自學寫過的程式放上來
留言
avatar-img
留言分享你的想法!

































































你可能也想看
從 Google News 追蹤更多 vocus 的最新精選內容