背景介绍
用户输入一组数字,系统将其分类为正数/负数/零,并自动计算平均值。这一功能需要基于列表进行数据处理,使用Python实现,无需依赖复杂框架。
思路分析
- 数据结构:采用Python的列表作为输入数据,用于存储和处理数字。
- 算法应用:
- 判断输入数字是否为零:使用
if语句检查元素是否等于0。 - 分类正负数:使用布尔判断(
>0或<0)决定分类。 - 计算平均值:遍历所有元素,累加并除以元素数量。
- 判断输入数字是否为零:使用
代码实现
def classify_and_calculate(numbers):
# 输入验证
if not numbers:
raise ValueError("Input list must not be empty.")
# 判断所有元素是否为零
zero_count = sum(1 for num in numbers if num == 0)
# 计算正负数和平均值
positive_numbers = sum(1 for num in numbers if num > 0)
negative_numbers = sum(1 for num in numbers if num < 0)
sum_positive = sum(num for num in numbers if num > 0)
average = sum_positive / sum(1 for num in numbers if num != 0)
# 输出结果
result = f"正数({positive_numbers}, {average})"
print(result)
# 示例输入
numbers = [1, 2, 3, 4, 5]
numbers = [5, 7, -3, 10, -10]
numbers = [0, 5, 0, 10, 0]
classify_and_calculate(numbers)
总结
本项目通过Python实现,利用列表和基础算法处理数字分类与平均值计算,确保代码简洁、可运行且符合中等难度的要求。核心技术点包括数据处理与算法应用,具体实现涉及判断条件、求和与除法运算。