如何解决“TypeError:unordered types:str()<int()”错误?

2024-04-20 08:31:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python的新手(我才14岁),我想为随机的整数列表创建一个气泡分类器。以下是我的代码:

list = input("Please put in a random set of integers, in any order you like (unlimited range), separated by spaces:")
list = list.split()

indexcounter = 0


def sorter(list, indexcounter):
    for v in list:
        int(v)
    while indexcounter < len(list) - 1:
        if list[indexcounter] <= list[indexcounter + 1]:
            indexcounter += 1
        else:
            b = list[indexcounter + 1]
            list[indexcounter + 1] = list[indexcounter]
            list[indexcounter] = b
            indexcounter += 1
            print(list)

indexcounter2 = 0


def checker(list, indexcounter2):
    for v in list:
        int(v)
    while indexcounter2 <= len(list) - 1:
        if list[indexcounter2] < len(list) - 1:
            if int(list[indexcounter2]) <= list[indexcounter2 + 1]:
                indexcounter2 += 1
        elif int(list[indexcounter2]) == len(list) - 1:
            print("Process finished." + list)
        else:
            sorter(list, indexcounter2)

sorter(list, indexcounter)
checker(list, indexcounter2)

基本上,如果列表中的一个整数小于它后面的那个,我继续检查列表中下一个值是否相同。如果没有,我会将列表中的两个项目替换为彼此。当这个过程完成后,我调用一个“checker”函数来查看列表是否按从最小到最大的顺序排列。如果是的话,我就打印完成的清单。如果没有,那么我再次运行分拣机功能。这会一直重复,直到列表完成。在

但是,我一直得到:

^{pr2}$

checker函数出错。我怎么解决这个问题?提前谢谢!在

我知道这不是最有效的分拣机,但我只需要完成这个项目。在


Tags: in列表forlenifdefchecker整数
1条回答
网友
1楼 · 发布于 2024-04-20 08:31:13

这种例外很可能是在这里提出的:

int(list[indexcounter2]) <= list[indexcounter2 + 1]

如果确定只处理数字,则可以在调用input后使用以下命令将列表中的所有元素更改为ints:

^{pr2}$

这接受int对象并将其映射到values.split中的每个值,如果{}中的值不能转换为int中的值,则将引发异常。在

如您所见,我没有对从input接收的值使用名称list,您也不应该使用该名称,listPython中的一个内置对象,通过将该名称分配给另一个值,您就屏蔽了该内置对象。所以把你的第一行改成:

values = input("Please put in a random set of integers, in any order you like (unlimited range), separated by spaces:")

相关问题 更多 >