【发布时间】:2022-01-14 03:35:36
【问题描述】:
我正在创建一个选择排序的代码,但是当我尝试它时,它说它无法比较 str 和 int。我需要帮助
def selection(collection):
for i in range(len(collection)):
#assume that the first element is the smallest
min_idx = i
print(collection)
for j in range(i+1, len(collection)):
#compare if following elements are smaller
if collection[min_idx] > collection[j]:
min_idx = j #if yes, get index
collection[i], collection[min_idx] = collection[min_idx], collection[i]
名单:
nlist = [19, 5, 'cat', 'rabbit', 2, 32, 'mice', 'dog', 7]
所需的输出:
[2, 5, 7, 19, 32, 'cat', 'dog', 'mice', 'rabbit']
错误:
TypeError: '>' not supported between instances of 'int' and 'str'
【问题讨论】:
-
您想获得什么订单?所有字符串在前,所有字符串在后,还有别的吗?
-
嗯,哪个更大 -
5或'rabbit'?为什么? -
请参阅minimal reproducible example 并相应地增强您的问题。含义:给我们所有相关代码,给我们异常堆栈跟踪。好吧,弄清楚你的要求。问问自己,当你要比较数字 19 和字符串“cat”时,你会如何排序? (提示:你不能。你只能对具有相同类型的列表条目进行排序)
-
您不能将字符串与整数进行比较。除非您定义如何比较
5和'rabbit',否则这是不可能的。 -
@alex 取决于兔子的大小,不是吗。一只小兔子可能不到 5 只,但一只大兔子,谁知道呢,也许只有 10 只?
标签: python selection-sort