【问题标题】:We need to do a selection sorter that can sort mixed variables list我们需要做一个可以对混合变量列表进行排序的选择排序器
【发布时间】: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


【解决方案1】:

您需要创建两个列表。一个包含整数,另一个包含字符串。对它们中的每一个进行排序,然后将它们重新组合在一起。你可以这样做:

nlist = [19, 5, 'cat', 'rabbit', 2, 32, 'mice', 'dog', 7]
dlist = [e for e in nlist if isinstance(e, int)]
clist = [e for e in nlist if not isinstance(e, int)]
answer = sorted(dlist) + sorted(clist)
print(answer)

如果您愿意,可以尝试使用自己的排序函数而不是内置的 sorted 函数

【讨论】:

  • 如果我希望输出的步骤如下:['19', '5', 'cat', 'rabbit', '2', '32', 'mice', 'dog', '7'] ['19', '5', 'cat', 'rabbit', '2', '32', 'mice', 'dog', '7'] ['19', '2', 'cat', 'rabbit', '5', '32', 'mice', 'dog', '7'] ['19', '2', '32', 'rabbit', '5', 'cat', 'mice', 'dog', '7'] ['19', '2', '32', '5', 'rabbit', 'cat', 'mice', 'dog', '7'] ['19', '2', '32', '5', '7', 'cat', 'mice', 'dog', 'rabbit'] ['19', '2', '32', '5', '7', 'cat', 'mice', 'dog', 'rabbit'] ['19', '2', '32', '5', '7', 'cat', 'dog', 'mice', 'rabbit']
  • 这是一个不同的问题。在您最初的问题中,您混合了字符串和整数。现在它们都是字符串。我建议您提出一个新问题,因为我的回答完全提供了您在原始问题中所需的输出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-07
  • 1970-01-01
  • 1970-01-01
  • 2014-06-21
  • 2010-12-06
  • 2018-10-17
相关资源
最近更新 更多