如何对正值排在负数之前的列表进行排序,负数分别与已排序的值排在一起? [英] How do I sort a list with positives coming before negatives with values sorted respectively?

查看:551
本文介绍了如何对正值排在负数之前的列表进行排序,负数分别与已排序的值排在一起?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含正负数字混合的列表,如下所示

I have a list that contains a mixture of positive and negative numbers, as the following

lst = [1, -2, 10, -12, -4, -5, 9, 2]

我要完成的工作是对列表进行排序,将正数排在负数之前,分别对负数进行排序.

What I am trying to accomplish is to sort the list with the positive numbers coming before the negative numbers, respectively sorted as well.

所需的输出:

[1, 2, 9, 10, -12, -5, -4, -2]

我能够弄清楚第一部分的排序是在正数和负数之前进行,不幸的是,这并没有分别对正数和负数进行排序.

I was able to figure out the first part sorting with the positive numbers coming before the and negative numbers, unfortunately this does not respectively sort the positive and negative numbers.

lst = [1, -2, 10, -12, -4, -5, 9, 2]
lst = sorted(lst, key=lambda o: not abs(o) == o)
print(lst)

>>> [1, 10, 2, 9, -2, -12, -4, -5]

如何使用pythonic解决方案实现所需的排序?

How may I achieve my desired sorting with a pythonic solution?

推荐答案

您可以只使用常规排序,然后在0处将列表一分为二:

You could just use a regular sort, and then bisect the list at 0:

>>> lst
[1, -2, 10, -12, -4, -5, 9, 2]
>>> from bisect import bisect
>>> lst.sort()
>>> i = bisect(lst, 0)  # use `bisect_left` instead if you want zeroes first
>>> lst[i:] + lst[:i]
[1, 2, 9, 10, -12, -5, -4, -2]

最后一行利用切片不变式lst == lst[:n] + lst[n:]

The last line here takes advantage of a slice invariant lst == lst[:n] + lst[n:]

另一种选择是使用元组作为排序键,并依靠词典排序元组:

Another option would be to use a tuple as a sort key, and rely on lexicographical ordering of tuples:

>>> sorted(lst, key=lambda x: (x<0, x))  # use <= instead if you want zeroes last
[1, 2, 9, 10, -12, -5, -4, -2]

这篇关于如何对正值排在负数之前的列表进行排序,负数分别与已排序的值排在一起?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆