gpt4 book ai didi

python - 对整数和字符串的混合列表进行排序

转载 作者:行者123 更新时间:2023-12-03 18:15:40 27 4
gpt4 key购买 nike

我正在尝试对以下整数和字符串的混合列表进行排序,但是却得到了一个 TypeError。我想要的输出顺序是排序整数然后排序字符串。

x=[4,6,9,'ashley','drooks','chay','poo','may']
>>> x.sort()
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
x.sort()
TypeError: '<' not supported between instances of 'str' and 'int'

最佳答案

您可以将自定义键功能传递给 list.sort :

x = [4,6,9,'ashley','drooks','chay','poo','may']
x.sort(key=lambda v: (isinstance(v, str), v))

# result:
# [4, 6, 9, 'ashley', 'chay', 'drooks', 'may', 'poo']

这个关键函数将列表中的每个元素映射到一个元组,其中第一个值是一个 bool 值( True 表示字符串, False 表示数字),第二个值是元素本身,如下所示:
>>> [(isinstance(v, str), v) for v in x]
[(False, 4), (False, 6), (False, 9), (True, 'ashley'), (True, 'chay'),
(True, 'drooks'), (True, 'may'), (True, 'poo')]

然后使用这些元组对列表进行排序。因为 False < True ,这使得整数在字符串之前排序。具有相同 bool 值的元素然后按元组中的第二个值排序。

关于python - 对整数和字符串的混合列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49829732/

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