dict_counter={}
for food in ['spam','spam','eggs','spam']:
if not food in dict_counter:
dict_counter[food]=0
dict_counter[food]+=1
for food,count in dict_counter.items():
print(food,count)
看不太懂為何初始值為何這樣打,not food 不是就表示若有非food元素出現才將dict_counter[food]設為零,但是實際執行應該會跳過這段吧
因為其實上面回答完了,所以提供個簡化的作法好了。
dict_counter={}
for food in ['spam','spam','eggs','spam']:
if not food in dict_counter:
dict_counter[food]=0
等同於:
foods = ['spam','spam','eggs','spam']
dict_counter = dict((food, 0) for food in set(foods))
甚至整段code可以變成一行:
count_foods = dict((food, foods.count(food)) for food in set(foods))
然後python的神奇之處在於一行的code比5行的還容易搞清楚。(茶