我有一个浮动列表:
inputlist = [4.1, 8.2, 2.1, 8.1, 3.1]
我需要它:
list_sorted = [8.1, 8.2, 2.1, 3.1, 4.1]
首先按升序编写其int(数字)相同的浮点数(int(8.1)== int(8.2)),然后按升序编写其余元素。
另一个例子:
inputlist = [9.3, 4.1, 4.2, 9.4, 8.2, 7.1]
list_sorted = [4.1, 4.2, 9.3, 9.4, 7.1, 8.2]
答案 0 :(得分:2)
您需要进行两次传递:一次计算整数部分,然后进行排序:
from collections import Counter
integer_counts = Counter(int(num) for num in inputlist)
list_sorted = sorted(inputlist, key=lambda n: (integer_counts[int(n)] == 1, n))
sort键产生一个首先使用布尔值的键(False
,对于多于1的值,只有一个值为True
),实际值为秒。这将这些值分组,其中整数部分首先出现多次:
>>> from collections import Counter
>>> inputlist = [4.1, 8.2, 2.1, 8.1, 3.1]
>>> integer_counts = Counter(int(num) for num in inputlist)
>>> sorted(inputlist, key=lambda n: (integer_counts[int(n)] == 1, n))
[8.1, 8.2, 2.1, 3.1, 4.1]
>>> inputlist = [9.3, 4.1, 4.2, 9.4, 8.2, 7.1]
>>> integer_counts = Counter(int(num) for num in inputlist)
>>> sorted(inputlist, key=lambda n: (integer_counts[int(n)] == 1, n))
[4.1, 4.2, 9.3, 9.4, 7.1, 8.2]
算法复杂度仍为O(NlogN);计数是一个O(N)步骤,然后是O(NlogN)排序,使整个过程为O(NlogN)。
答案 1 :(得分:1)
这有什么价值吗?
inputlist = [4.1, 8.2, 2.1, 8.1, 3.1]
def srt (lst):
chkdict = {}
for x in lst:
y = int(x)
if not y in chkdict: chkdict[y] = [x]
else: chkdict[y].append(x)
left = []; right = []
for x in chkdict.values():
if len(x)>1: left += x
else: right += x
left.sort(); right.sort()
return left+right
>>> ["%.1f" % x for x in srt(inputlist)]
['8.1', '8.2', '2.1', '3.1', '4.1']
注意:我使用字符串格式来强制更好看。
这不是最有效的方法,但它适用于中小型列表。它使用了与collections.Counter()中的一些相同的机制。