Python中vec.append失效,列表始终为空问题求助
问题解决:CARGAR函数append数据后列表仍为空的原因及修复方案
核心问题:重复调用main()导致列表被重置
在cargar函数的最后一行调用了main(),这会重新执行main函数,而main函数第一行就是vec = [],直接把之前添加了数据的列表覆盖成空列表——这就是append操作后列表仍然为空的根本原因。
其他需要修复的问题
validar_positivo函数循环逻辑错误:当输入的n≤0时,仅打印错误但未重新获取输入,会陷入死循环。ordenar函数访问错误:vec中的元素是元组,不能用.tiempo_t的属性方式访问,且原代码将平均时间转为字符串,无法正确进行数值排序。
修复后的完整代码
import random def mostrar_menu(): print("-------------------------------------------------------------------------") print(" MENU ") print("1. Cargar ") print("2. Listar ") print("-------------------------------------------------------------------------") def validar_positivo(): n = int(input("Cuantos corredores hay?: ")) while n <= 0: print("ERROR! Numero invalido") n = int(input("Ingrese nuevamente el numero de corredores: ")) return n def cargar(n, vec): for i in range(n): numero = str(i+1) nombre = input("Ingrese el nombre del corredor " + numero + ": ") tiempo_1 = random.randint(0, 60) tiempo_2 = random.randint(0, 60) tiempo_3 = random.randint(0, 60) suma_t = tiempo_1 + tiempo_2 + tiempo_3 tiempo_t = suma_t / 3 print("Su tiempo promedio es de", tiempo_t) # 保留数值类型方便后续排序,无需全部转字符串 carrera = (nombre, tiempo_1, tiempo_2, tiempo_3, tiempo_t) vec.append(carrera) # 移除此处的main()调用 def ordenar(vec): n = len(vec) for i in range(0, n-1): for j in range(i+1, n): # 通过索引访问元组中的平均时间,直接用数值比较 if vec[i][4] < vec[j][4]: vec[i], vec[j] = vec[j], vec[i] def main(): vec = [] a = 0 while a != 3: mostrar_menu() a = int(input("Ingrese su opcion: ")) if a == 1: n = validar_positivo() cargar(n, vec) elif a == 2: ordenar(vec) if not vec: print("Llene la lista") else: print(vec) elif a == 3: print("Adios!") else: print("Opcion invalida, ingrese nuevamente") if __name__ == "__main__": main()
修复说明
- 移除
cargar函数末尾的main()调用,避免重置列表。 - 修复
validar_positivo的循环逻辑,确保用户输入有效正数。 - 修改
ordenar函数的元组访问方式,保留数值类型以便正确排序。 - 优化输入处理,input返回的本身就是字符串,无需额外转str。
- 增加无效选项提示,提升用户交互体验。
内容的提问来源于stack exchange,提问作者Nano Casas
相关产品推荐
相关产品推荐

