首页 > 解决方案 > How to sort tuples like this?

问题描述

data = [ (2,2), (0,5), (8,0), (9,8), (7,14), (13,12), (14,13) ]

I want this tuple list to be sorted like this:

data = [ (14,13), (7,14), (13,12), (9,8), (8,0), (0,5), (2,2) ]

The order is following:

[ [(coordinates with largest X)],[(coordinates with largest Y)], [(coordinates with second largest X)], [(coordinates with second largest Y)], [(Third Largest X)], [(Third Largest y)] ... and so on ]

I tried to use

data.sort(key=lambda x:x[0],reverse=True)

first, and then

data.sort(key=lambda x:x[1],reverse=True)

but it does not work.

What do you think I have to do? Please help

标签: pythonsortinglambda

解决方案


这是使用 Numpy 的解决方案:

import numpy as np

data = [ (2,2), (0,5), (8,0), (9,8), (7,14), (13,12), (14,13) ]

d = np.array(data)

d_xy = [np.argsort(d[:, 0])[::-1],
        np.argsort(d[:, 1])[::-1]]

idx_xy = [0, 0] 

alternator = 0

order = []

for k in range(d.shape[0]):

    idx = idx_xy[alternator]

    while (d_xy[alternator][idx] in order):

        idx += 1

    order.append(d_xy[alternator][idx])
    alternator = 1 - alternator
    idx_xy[alternator] = idx

print(d[order])

结果:

[[14 13]
 [ 7 14]
 [13 12]
 [ 9  8]
 [ 8  0]
 [ 0  5]
 [ 2  2]]

推荐阅读