如何将第n个元素的元组列表按最接近的值分组?

时间:2019-02-08 15:51:17

标签: python-3.x list group-by tuples

我有一个看起来像这样的元组列表:

d = [(1,1,1),
     (2,1,1),
     (1,2,1),
     (1,12,1),
     (13,50,4),
     (1,13,32),
     (4,48,100),
     (0,121,5)
]

然后将此列表按每个元组的第一个元素的最接近值进行分组,如下所示:

d_ordered = [
     [(1,1,1),(2,1,1),(1,2,1)],
     [(1,12,1),(1,13,32)],
     [(4,48,100),(13,50,4)],
     [(0,121,5)]
]

我发现了这一点:https://stackoverflow.com/a/10017017/9071615 这是一个简单的列表。我试图以此为基础,但不知道如何将解决方案扩展到元组列表。

有人知道如何对元组列表进行最有效的排序吗?

2 个答案:

答案 0 :(得分:0)

这是使用sorted()lambda的解决方案:

d = [(1,1,1),
     (2,1,1),
     (1,2,1),
     (1,12,1),
     (13,50,4),
     (1,13,32),
     (4,48,100),
     (0,121,5)
]

d_ordered = sorted(d, key = lambda x: (x[1]))

print(d_ordered)

输出:

[(1, 1, 1), (2, 1, 1), (1, 2, 1), (1, 12, 1), (1, 13, 32), (4, 48, 100), (13, 50, 4), (0, 121, 5)]

答案 1 :(得分:0)

import numpy as np
from itertools import  groupby
n = 1
a = np.array([i[n] for i in d])# or np.array(d)[:,n] if all the elements of d have the same shape
b,c=np.where(np.abs(a-a[:,None]) < 5)# I used a maximum distance of 5, you did not specify exactly the allowable distance
e=set(tuple(k[1] for k in j) for i,j in groupby(zip(b,c),key=lambda x:x[0]))
[[d[j] for j in i] for i in e]

[[(1, 1, 1), (2, 1, 1), (1, 2, 1)],
 [(0, 121, 5)],
 [(13, 50, 4), (4, 48, 100)],
 [(1, 12, 1), (1, 13, 32)]]