Files
2025PY/day15/03-列表遍历的应用.py
2025-05-22 16:50:44 +08:00

31 lines
1.3 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 列表遍历的应用
# 1.创建一个列表里面包含1-100里面的偶数每5个数求平均数且把求的平均值放到一个新列表中.
# 分析
# 第一步生成一个列表里面是1-100的偶数
list = [] # 存放1-100的偶数
for i in range(1,101): # 循环产生1-100
if i % 2 == 0: # i是偶数
list.append(i) # 将偶数逐个追加到list列表中
print(list)
# [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30, 32, 34, 36, 38, 40, 42, 44, 46, 48, 50, 52, 54, 56, 58, 60, 62, 64, 66, 68, 70, 72, 74, 76, 78, 80, 82, 84, 86, 88, 90, 92, 94, 96, 98, 100]
# 第二步列表里面每5个数求平均数追加给一个新的列表
# 分析列表,通过索引下标找到计算平均值的结束点
# 必须对列表进行遍历
result = 0 # 累加初始值
new_list = [] # 存放平均数的新列表
for index in range(len(list)): # 遍历列表,同时需要列表的索引 (index 每一个元素的索引)
result += list[index] # 累加所有列表的值
if (index + 1) % 5 == 0: # 求平均数的结束点
new_list.append(result / 5) # 求平均值,放到新的列表中
result = 0 # 一旦求得平均值重置result下次重新开始计算
print(new_list) # [6.0, 16.0, 26.0, 36.0, 46.0, 56.0, 66.0, 76.0, 86.0, 96.0]