gpt4 book ai didi

python - 如何解决 "TypeError: unorderable types: str() < int()"错误?

转载 作者:太空宇宙 更新时间:2023-11-03 16:22:38 24 4
gpt4 key购买 nike

我是 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)

基本上,如果列表中的一个整数小于它后面的整数,我会继续检查列表中下一个值的情况。如果没有,我将列表中的两项替换。当该过程完成后,我调用一个“检查器”函数来查看列表是否按最小到最大的顺序排列。如果是,那么我打印完成的列表。如果没有,那么我再次运行排序器功能。这会一直重复,直到列表完成。

但是,我不断收到:

TypeError: unorderable types: str() < int() 

检查器功能出错。我该如何解决?提前致谢!

我意识到这不是最有效的排序器,但我只需要完成这个项目。

最佳答案

该异常很可能在这里引发:

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

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

nums = list(map(int, values.split()))

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

如您所见,我没有使用名称 list 来表示从 input 接收到的值,并且您也不应该这样做list 是 Python 中的内置对象,通过将该名称分配给另一个值,您可以屏蔽该内置对象。因此,将第一行更改为:

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

关于python - 如何解决 "TypeError: unorderable types: str() < int()"错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38277151/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com