僅需計算一次的迴圈
一個整數清單 generations 已載入至你的工作階段,其中每個整數代表一個 Pokémon 的世代。你想要彙整各世代的出現次數,並計算每個世代占整體整數筆數的百分比。
以下這段迴圈用來完成此任務:
for gen,count in gen_counts.items():
total_count = len(generations)
gen_percent = round(count / total_count * 100, 2)
print(
'generation {}: count = {:3} percentage = {}'
.format(gen, count, gen_percent)
)
讓我們把只需要計算一次的運算移到迴圈外,使這段迴圈更有效率。
本練習屬於課程
撰寫高效的 Python 程式碼
練習說明
- 從
collections模組匯入Counter。 - 使用
Counter()從清單generations彙整各世代的出現次數,並將結果存為gen_counts。 - 撰寫更好的 for 迴圈,將「只需計算一次」的運算移到迴圈外(上方)。請使用與原本 for 迴圈完全相同的語法(直接將該一次性運算複製貼到迴圈上方即可)。
動手互動練習
試著完成這個範例程式碼,體驗一下這個練習。
# Import Counter
____
# Collect the count of each generation
gen_counts = ____
# Improve for loop by moving one calculation above the loop
total_count = ____
for gen,count in gen_counts.items():
gen_percent = round(count / total_count * 100, 2)
print('generation {}: count = {:3} percentage = {}'
.format(gen, count, gen_percent))