我有一个花车清单:
inputlist = [4.1, 8.2, 2.1, 8.1, 3.1]
我需要它是:
list_sorted = [8.1, 8.2, 2.1, 3.1, 4.1]
通过首先按升序编写其int(number)相同的浮点数(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]
最佳答案
您需要进行两次通过:一次计算整数部分,然后进行排序:
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))
排序键产生的键首先是布尔值(
False
是多个值的整数,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)。
关于python - 如何对列表进行排序,首先写入相同的元素,然后-按升序排列,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32897215/