題目連結

https://zerojudge.tw/ShowProblem?problemid=a743

https://onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=16&page=show_problem&problem=1361

參考文章

X

本題要點

問輸入的國家出現多少次,所以把重點聚焦在計算國家出現幾次就可以了

人名可以直接忽略,split(" ", 1) 的意思是遇 ” “(空格)就分割出一個

這樣我們只會記錄到 country,後面一串人名會直接忽略他(反正用不到XD)

每一行輸入後去判斷他是否在字典集 CTcount 當中

如果已經存在,就將他的值 +1

如果不存在,就將次數設為 1(也就是加入字典)

最後將資料按照字母排序(題目要求),直接用 sorted 就可以了~

參考解答

解一:

截圖 2024-06-24 下午3.42.41.png

n = int(input())
CTcount = {}
for _ in range(n):
	country, _ = input().split(" ", 1)  # 讀取國家和剩餘的部分
	if country in CTcount:
		CTcount[country] += 1  # 如果在字典中,次數加1
	else:
		CTcount[country] = 1  # 如果不在字典中,將次數設為1
		
for OP in sorted(CTcount):
	print(f"{OP} {CTcount[OP]}")