練習一:基本陣列走訪Traversal
題目描述
建立數列 [10, 20, 30, 40, 50],依序輸出每個元素。
解題思路
- 建立 List。
- 使用 for 逐一取得元素。
- 輸出元素。
Python 程式
numbers = [10, 20, 30, 40, 50]
for x in numbers:
print(x)執行結果
10 20 30 40 50
建立數列 [10, 20, 30, 40, 50],依序輸出每個元素。
numbers = [10, 20, 30, 40, 50]
for x in numbers:
print(x)10 20 30 40 50
已知五筆成績,求總分與平均。
scores = [80, 70, 90, 65, 85]
sum_score = 0
for score in scores:
sum_score += score
avg = sum_score / len(scores)
print("總分 =", sum_score)
print("平均 =", avg)總分 = 390 平均 = 78.0
找出陣列中的最大值與最小值。
先以第一個元素當作目前最大/最小值,再逐一比較。
data = [12, 7, 35, 4, 21]
max_value = data[0]
min_value = data[0]
for x in data:
if x > max_value:
max_value = x
if x < min_value:
min_value = x
print("最大值 =", max_value)
print("最小值 =", min_value)最大值 = 35 最小值 = 4
在 List 中搜尋 70,找到就輸出索引位置,找不到則輸出「不存在」。
data = [10, 30, 50, 70, 90]
target = 70
position = -1
for i in range(len(data)):
if data[i] == target:
position = i
break
if position >= 0:
print("索引 =", position)
else:
print("不存在")索引 = 3
統計數字 2 在陣列中出現幾次。
data = [1, 2, 3, 2, 4, 2, 5]
target = 2
count = 0
for x in data:
if x == target:
count += 1
print(count)3
使用二維 List 儲存兩位學生的三科成績,逐列計算每位學生總分。
外層走訪每位學生,內層走訪該學生的各科成績。
scores = [
[80, 75, 90],
[60, 88, 72]
]
for student in scores:
total = 0
for score in student:
total += score
print(total)245 220