python - 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
解决方案
这是使用 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]]
推荐阅读
- mitmproxy - Mac 上 mitmproxy==0.11.3 中的问题
- javascript - 自动将附属标识符添加到 URL
- python - python - 使用 selenium chromedriver 库在网站数据中按元素查找链接
- python - 如何在不使用熊猫数据框的情况下将列名添加到 ipysheet?
- ios - 如何使视图可滚动 - 视图包含带有标签和图像的堆栈?
- python - lin_reg.coef_ 函数在使用 StandardScaler 缩放训练数据时返回过高的系数
- sql - 如何获取每年点的名称和最大总和值?
- docker - Ubuntu docker-compose 错误 Compose 文件版本
- javascript - 在 facebook 上共享时,角度应用程序中的 og 元标记不起作用
- java - 如何使用现有的 android 应用程序并响应本机 UI?