Files
2025PY/day15/04-列表的遍历练习.py
2025-05-22 16:50:44 +08:00

59 lines
2.1 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. 打印列表中的偶数
# 给定一个整数列表,遍历该列表并打印出其中所有的偶数。
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
for num in numbers:
if num % 2 == 0:
print(num)
# 1. 打印列表中的偶数
# 给定一个整数列表,遍历该列表并打印出其中所有的偶数。
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total = total + num
print(total)
# 3. 找出列表中的最小元素
# 给定一个整数列表,遍历该列表找出其中最小的元素并打印出来。
numbers = [23, 12, 45, 6, 34]
min_num = numbers[0]
for num in numbers:
if num < min_num:
min_num = num
print(min_num)
# 4. 生成新列表,包含原列表元素的平方
# 有一个整数列表,遍历该列表,将每个元素进行平方运算,然后将结果存储到一个新列表中,最后打印新列表。
numbers = [1, 2, 3, 4, 5]
squared_numbers = []
for num in numbers:
squared_numbers.append(num ** 2)
print(squared_numbers)
# 5. 统计列表中每个元素出现的次数
# 给定一个包含重复元素的列表,遍历该列表统计每个元素出现的次数,并将结果以字典的形式打印出来,字典的键为列表中的元素,值为该元素出现的次数。
fruits = ['apple', 'banana', 'apple', 'cherry', 'banana', 'apple']
fruit_count = {}
for fruit in fruits:
if fruit in fruit_count:
fruit_count[fruit] = fruit_count[fruit] + 1
else:
fruit_count[fruit] = 1
print(fruit_count)
# 6. 合并两个列表中的元素,按顺序交替插入
# 有两个列表 list1 和 list2遍历这两个列表将它们的元素按顺序交替插入到一个新列表中。如果其中一个列表较长将其剩余元素直接添加到新列表的末尾最后打印新列表。
list1 = [1, 3, 5]
list2 = [2, 4, 6, 8]
merged_list = []
min_len = min(len(list1), len(list2))
for i in range(min_len):
merged_list.append(list1[i])
merged_list.append(list2[i])
if len(list1) > len(list2):
merged_list.extend(list1[min_len:])
else:
merged_list.extend(list2[min_len:])
print(merged_list)