根据列表中的多个元素对列表进行排序

时间:2017-11-28 17:14:31

标签: python python-3.x sorting

是否可以根据多个列表元素实现python键进行排序?

例如:

list = [1, 2, 3, 4]

我想根据两个元素之间的差异对列表进行排序,以便在它们之间最大化delta。

预期结果:

list = [1, 4, 2, 3] # delta = 4-1 + 4-2 + 3-2 = 6

其他结果也是可能的,但是1在原始数组中是4之前,所以应该首先采用1:

list = [4, 1, 3, 2] # delta = 4-1 + 3-1 + 3-2 = 6

我想使用python sorted,如:

sorted(list, key=lambda e1, e2: abs(e1-e2))  

有可能这样做吗?也许还有另一个可以使用的库。

2 个答案:

答案 0 :(得分:2)

这种解决方案非常暴力;但是,它仍有可能:

from itertools import permutations
list = [1, 2, 3, 4]
final_list = ((i, sum(abs(i[b]-i[b+1]) for b in range(len(i)-1))) for i in permutations(list, len(list)))
final_lists = max(final_list, key=lambda x:x[-1])

输出:

((2, 4, 1, 3), 7)

请注意,输出格式为:(list, total_sum))

答案 1 :(得分:2)

由于(如您所示)可能会有多种不同的结果 - 这意味着此排序/顺序不具有确定性,因此您无法对其应用关键功能。

也就是说,自己实现排序很容易:

def my_sort(col):
    res = []
    while col:
        _max = max(col)
        col.remove(_max)
        res.append(_max)

        if col:
            _min = min(col)
            col.remove(_min)
            res.append(_min)

    return res


print(my_sort([1,2,3,4]))  # [4, 1, 3, 2]

此解决方案在O(n^2)中运行,但可以通过在开头排序col来改进,然后不是查找maxmin我们可以提取项目列表的开头和结尾。通过这样做,我们会将时间复杂度降低到O(n log(n))

编辑

根据您的评论如下:如果索引发挥作用,那么它不是真正的"真实的"排序:)说,这个解决方案可以设计为先保持较小的索引等等:

def my_sort(col):
    res = []
    while col:
        _max = max(col)
        max_index = col.index(_max)
        col.remove(_max)

        if col:
            _min = min(col)
            min_index = col.index(_min)
            col.remove(_min)
            if max_index < min_index:
                res.extend([_max, _min])
            else:
                res.extend([_min, _max])
            continue
        res.append((_max))

    return res

print(my_sort([1,2,3,4])) # [1, 4, 2, 3]
相关问题