如何在Python中首先按字母顺序对字符串列表进行排序,然后按数字顺序进行排序?
例如:
Given list: li = ['4', '1', '3', '9', 'Z', 'P', 'V', 'A']
排序后我想要以下输出:
sorted_list = ['A', 'P', 'V', 'Z', '1', '3', '4', '9']
答案 0 :(得分:6)
sorted(sorted_list, key=lambda x: (x.isnumeric(),int(x) if x.isnumeric() else x))
这也按整数值排序
答案 1 :(得分:3)
您可以尝试一下。通过使用str.isdigit
sorted(l,key=lambda x:(x.isdigit(),x))
# ['A', 'P', 'V', 'Z', '1', '3', '4', '9']
注意::此解决方案不能处理多个数字。请查看@Martin's的答案。
答案 2 :(得分:0)
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 + number
print(list1)
答案 3 :(得分:0)
如果您希望它考虑负数,小数和小写字母:
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') + 1
sorted_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']