Files
2025PY/day12/02-作业.py
2025-05-22 16:50:44 +08:00

50 lines
1.2 KiB
Python

# 1. 计算数列的和
numbers = [2, 4, 6, 8, 10]
total = 0
for num in numbers:
total += num
print(f"数列的和是 {total}")
# 2. 统计字符串中字符出现的次数
s = input("请输入字符串:")
char_count = {}
for char in s:
char_count[char] = char_count.get(char, 0) + 1
for char, count in char_count.items():
print(f"{char}: {count}")
# 3. 找出列表中的所有偶数
lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []
for num in lst:
if num % 2 == 0:
even_numbers.append(num)
print("偶数有:", *even_numbers)
# 4.计算列表中所有数字的平方
lst = [1, 2, 3, 4, 5]
squared_list = []
for num in lst:
squared_list.append(num ** 2)
print(f"平方后的列表是:{squared_list}")
# 5.计算字符串的反向
s = input("请输入一个字符串:")
reversed_str = ""
for char in s:
reversed_str = char + reversed_str
print(f"反转后的字符串是:{reversed_str}")
# 6.找出数组中的重复元素
arr = [1, 2, 3, 4, 2, 5, 3]
duplicates = []
for i in range(len(arr)):
if arr[i] in arr[:i] and arr[i] not in duplicates:
duplicates.append(arr[i])
print("重复的元素有:", *duplicates)