【问题标题】:sort array python both int and string排序数组 python int 和 string
【发布时间】:2023-01-20 00:57:58
【问题描述】:
a= ["house", "horse", 1, "cat", 2]

有办法订购吗?

前任。 a.sort()sorted(a) 这种失败的方法 帮助?

方法排序() 方法.sort() 失败

【问题讨论】:

  • 你要找什么订单?
  • 字符串和数字应该如何相互比较?
  • 如果你想把数字当作字符串,你可以使用key=str。但这会将 10 排在 2 之前。
  • 在 python 中,这是一个列表,而不是数组。

标签: python arrays sorting


【解决方案1】:

是的,有一种方法可以在 Python 中对包含整数和字符串的数组进行排序。当尝试对包含整数和字符串的列表进行排序时,内置的 sorted() 函数和列表方法 sort() 将引发 TypeError。

您可以使用 sorted() 函数的 key 参数来指定一个函数,该函数将用于从列表的每个元素中提取排序键。键函数应该返回一个可以与其他元素的键进行比较的值。

例如,您可以使用 str() 函数将所有元素转换为字符串来对列表进行排序:

a = ["house", "horse", 1, "cat", 2]
a = sorted(a, key=str)
print(a) # Output: [1, 2, 'cat', 'horse', 'house']

【讨论】:

    猜你喜欢
    • 2019-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多