Python循环练习题:挑战你的编程技巧
Python循环练习题:挑战你的编程技巧
以下三道Python循环练习题,涵盖重复项查找、字符计数和平均值计算,适合有一定编程基础的学习者练习,挑战你的编程思维,提升代码能力。
1. 找出列表中的重复项
编写一个程序,找出给定列表中的所有重复项,并将它们存储在一个新列表中。例如,如果列表为[1, 2, 3, 2, 1, 4, 5, 4],则程序应该返回[1, 2, 4]。
答案:
def find_duplicates(lst):
duplicates = []
for i in range(len(lst)):
for j in range(i+1, len(lst)):
if lst[i] == lst[j] and lst[i] not in duplicates:
duplicates.append(lst[i])
return duplicates
lst = [1, 2, 3, 2, 1, 4, 5, 4]
print(find_duplicates(lst))
2. 字符计数
编写一个程序,接受一个字符串,并计算其中每个字符出现的次数。例如,如果输入的字符串为'hello',则程序应该返回{'h': 1, 'e': 1, 'l': 2, 'o': 1}。
答案:
def count_chars(s):
counts = {}
for char in s:
if char in counts:
counts[char] += 1
else:
counts[char] = 1
return counts
s = 'hello'
print(count_chars(s))
3. 计算列表元素的平均值
编写一个程序,接受一个整数列表,并返回其中所有元素的平均值。例如,如果列表为[1, 2, 3, 4, 5],则程序应该返回3.0。
答案:
def average(lst):
total = 0
for num in lst:
total += num
return total / len(lst)
lst = [1, 2, 3, 4, 5]
print(average(lst))
挑战你的代码能力,试试看吧!
原文地址: https://www.cveoy.top/t/topic/ndRX 著作权归作者所有。请勿转载和采集!