先按字母顺序排序列表,然后再按数字排序?

如何在 Python 中先按字母顺序然后按数字对字符串列表进行排序?

例如:

Given list: li = ['4', '1', '3', '9', 'Z', 'P', 'V', 'A']

排序后我想要以下输出:

sorted_list = ['A', 'P', 'V', 'Z', '1', '3', '4', '9']


尚方宝剑之说
浏览 103回答 4
4回答

慕桂英4014372

sorted(sorted_list, key=lambda x: (x.isnumeric(),int(x) if x.isnumeric() else x))这也按整数的值排序

翻翻过去那场雪

你可以试试这个。可以通过使用来实现所需的输出str.isdigitsorted(l,key=lambda x:(x.isdigit(),x))# ['A', 'P', 'V', 'Z', '1', '3', '4', '9']注意:此解决方案不处理多于一个的数字。请看一下@Martin 的回答。

慕尼黑的夜晚无繁华

如果你想让它考虑负数、小数和小写字母:li = ['A', 'b', '-400', '1.3', '10', '42', 'V', 'z']threshold = abs(min(float(x) for x in li if not x.isalpha())) +  ord('z') + 1sorted_list = sorted(li,                     key=lambda x: ord(x) if x.isalpha() else threshold + float(x))sorted_list:['A', 'V', 'b', 'z', '-400', '1.3', '10', '42']

有只小跳蛙

list1 = ['4', '1', '3', '9', 'Z', 'P', 'V', 'A']number = []alphabet = []for l in list1:    if l.isnumeric():        number.append(l)    else:        alphabet.append(l)number = sorted(number)alphabet = sorted(alphabet)list1 = alphabet + numberprint(list1)输出
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python