You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python冒泡排序类报错:TypeError缺失位置参数lst,求问题排查

冒泡排序代码错误修复

你的代码报错核心有两个问题:

  1. sort()和display()方法定义时要求传入lst参数,但调用时未传递,导致TypeError。
  2. read()方法中创建的lst是局部变量,方法执行完毕后就会被销毁,其他方法无法访问到这个列表。

修改后的完整代码:

class BubbleSort1:

    def __init__(self) -> None:
        self.lst = []  # 初始化实例变量,用于共享列表数据

    def read(self):
        n1 = int(input('Enter the number of values to be sorted:'))
        print('Enter the values to be sorted')
        for i in range(n1):
            ele = int(input())
            self.lst.append(ele)
        print('Unsorted list:')
        print(self.lst)

    def sort(self):
        # 直接使用实例变量self.lst
        for i in range(len(self.lst)-1, 0, -1):
            for j in range(i):
                if self.lst[j] > self.lst[j+1]:
                    self.lst[j], self.lst[j+1] = self.lst[j+1], self.lst[j]  # 简化交换写法

    def display(self):
        print('Sorted list:')
        print(self.lst)  # 打印排序后的列表,而非长度

object1 = BubbleSort1()
object1.read()
object1.sort()
object1.display()

修改细节说明:

  • 实例变量共享数据:在__init__中定义self.lst,让read、sort、display三个方法都能操作同一个列表,避免局部变量无法共享的问题。
  • 移除冗余参数:sort和display方法不再需要传入lst参数,直接使用实例变量即可,调用时也就不用传参了。
  • 简化交换逻辑:把传统的临时变量交换改成Python特有的元组解包交换,代码更简洁。
  • 修正输出内容:display方法原来打印的是列表长度,现在改为打印排序后的列表内容,符合功能需求。

测试运行示例:

Enter the number of values to be sorted:5
Enter the values to be sorted
5
4
3
2
1
Unsorted list:
[5, 4, 3, 2, 1]
Sorted list:
[1, 2, 3, 4, 5]

内容的提问来源于stack exchange,提问作者Abekehw Qwta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.25 21:51:26