Python项目求助:如何向4×8的NumPy二维数组添加乘客年龄
问题解决:用NumPy二维数组模拟公交座位添加乘客
错误原因分析
你遇到的 AttributeError: 'numpy.ndarray' object has no attribute 'np' 是因为错误调用了numpy的append方法——np.append是numpy库的顶层函数,不是ndarray对象的属性,不能写成passenger_ages.np.append()。
另外,你的逻辑有核心问题:用np.append会改变数组形状,而项目要求是固定4×8的二维数组模拟座位,应该找到数组中未被占用的座位(值为0的位置),将年龄填入对应的位置,而非追加元素。
修正后的代码
import numpy as np # 初始化4行8列的二维数组,0代表空座位 passenger_ages = np.zeros([4, 8], dtype=int) class Bus: @staticmethod def run(): print('==============================') print('Welcome to the bus simulator') print('==============================') print('What do you want to do?') print('1. Add passenger.') print('2. Print all passengers.') print('3. See other age options') try: choice = int(input('Make your choice: ')) match choice: case 1: Bus.add_passenger() case 2: Bus.print_all() case 3: Bus.age_numbers() except ValueError: print('请输入有效数字选项') Bus.run() @staticmethod def print_all(): print("当前公交车座位年龄分布(0为空座位):") print(passenger_ages) Bus.run() @staticmethod def age_numbers(): print('What do you want to see?') print('1. Combined age.') print('2. Average age.') print('3. Oldest on the bus.') print('4. Youngest on the bus.') try: sub_choice = int(input('Make your choice: ')) # 过滤掉空座位(0) occupied_ages = passenger_ages[passenger_ages != 0] if len(occupied_ages) == 0: print("暂无乘客,请先添加乘客") Bus.run() return match sub_choice: case 1: print(f"所有乘客总年龄:{occupied_ages.sum()}") case 2: print(f"乘客平均年龄:{occupied_ages.mean():.2f}") case 3: print(f"最年长者年龄:{occupied_ages.max()}") case 4: print(f"最年轻者年龄:{occupied_ages.min()}") except ValueError: print('请输入有效数字选项') Bus.run() @staticmethod def add_passenger(): # 找到所有空座位的索引 empty_seats = np.where(passenger_ages == 0) if len(empty_seats[0]) == 0: print('公交车已满,无法添加乘客') Bus.run() return try: age = int(input('输入乘客年龄:')) if age <= 0: print('年龄必须为正整数') Bus.add_passenger() return # 取第一个空座位填入年龄 row, col = empty_seats[0][0], empty_seats[1][0] passenger_ages[row][col] = age print(f'已添加年龄为{age}的乘客,座位位置:第{row+1}排,第{col+1}座') again = input('是否继续添加乘客?(J/N)') if again.lower() == 'j': Bus.add_passenger() else: Bus.run() except ValueError: print('请输入有效的数字年龄') Bus.add_passenger() Bus.run()
关键修改点说明
- 修复append调用错误:不再用
np.append,而是通过np.where找到空座位(值为0的位置),直接给对应索引赋值 - 完善座位状态判断:添加乘客前先检查是否还有空座位,避免超出4×8的座位限制
- 修正类方法:添加
@staticmethod装饰器,使类方法调用更规范 - 补充年龄计算逻辑:在
age_numbers中实现了总年龄、平均年龄等功能,同时过滤空座位的0值 - 增加输入校验:对选项输入、年龄输入做了合法性判断,提升程序鲁棒性
内容的提问来源于stack exchange,提问作者Hesuchristo
相关产品推荐
相关产品推荐

