python列表排序

我有一个列表,需要对他进行排序,排序的要求是:正数、负数、小写字母、大写字母,同时正数需要由小到大,负数由大到小,小写字母正序,大写字母逆序
比如:输入[3, 1, 'g', -1, -9, -5, 'a', 'b', 'c', 'D', 'A']
输出:[1, 3, -1, -5, -9, 'a', 'b', 'c', 'g', 'D', 'A']
我现在的答案是这样的:

str1 =[3, 1, 'g', -1, -9, -5, 'a', 'b', 'c', 'D', 'A']
str2 = []
str3 = []
str4 = []
for i in str1:
    if isinstance(i, int):
        str2.append(i)
    elif 'a' <= i <= 'z':
        str3.append(i)
    else:
        str4.append(i)
str2.sort(key=lambda x: (x >= 0, x) and (x < 0, abs(x)))
str3.sort()
str4.sort(reverse=True)
str1 = str2 + str3 + str4

但是感觉写的太乱太复杂了,各位能帮忙简化一下吗

思路很多,比如说先用 filter 将各种类型分开,分别排序,再连接

str1 = [3, 1, 'g', -1, -9, -5, 'a', 'b', 'c', 'D', 'A']

pn = list(filter(lambda x: isinstance(x, int) and x >= 0, str1))
nn = list(filter(lambda x: isinstance(x, int) and x < 0, str1))
ll = list(filter(lambda x: isinstance(x, str) and x.islower(), str1))
ul = list(filter(lambda x: isinstance(x, str) and x.isupper(), str1))

pn.sort()
nn.sort(reverse=True)
ll.sort()
ul.sort(reverse=True)

sorted_list = pn + nn + ll + ul

print(sorted_list)

img

  用列表解析,让您的代码更优雅。


  用if type(i) is int and i > 0解析出正整数,if type(i) is int and i < 0解析出负整数,再用字符串方法str.islower()、str.isuper()解析出大小写字母,接下来来题目规则正序逆序正序逆序用sort()方法排序解析出的列表,最后用+运算符拼接排序后的列表。

  • 代码运行效果截屏图片

    img

  • python 代码
#!/sur/bin/nve python
# coding: utf-8
 
str1 =[3, 1, 'g', -1, -9, -5, 'a', 'b', 'c', 'D', 'A']
print('\n列表:\n', str1) 
str2 = [i for i in str1 if type(i) is int and i > 0] # 解析正整数。
str22 = [i for i in str1 if type(i) is int and i < 0] # 解析负整数。
str3 = [i for i in str1 if str(i).islower()] # 解析小写字母。
str4 = [i for i in str1 if str(i).isupper()] # 解析大写字母。
print(f"\n数字:{str2}\n小写字母:{str3}\n大写字母:{str4}") 
[i.sort() for i in (str2, str3)] # 数字、小写字母排正序。
[i.sort(reverse=True) for i in (str22, str4)] # 负整数、大写字母排逆序。
print(f"\n按规则排序后拼接:\n{str2 + str22+ str3 + str4}") # 可以用列表+运算拼接列表。