Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/285.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 按值对列表进行分组,并保留这两个值_Python - Fatal编程技术网

Python 按值对列表进行分组,并保留这两个值

Python 按值对列表进行分组,并保留这两个值,python,Python,我有一个列表,其中包含xy点的元组对(作为元组)。第一个表示任意点,第二个表示距离该点最近的簇的质心 all_neighbours = [((28, 145), (25, 125)), ((65, 140), (44, 105)), ((50, 130), (25, 125)), ((38, 115), (44, 105)), ((55, 118), (44, 105)), ((50, 90), (44, 105)), ((63, 88 ), (44, 105)), ((43, 83

我有一个列表,其中包含xy点的元组对(作为元组)。第一个表示任意点,第二个表示距离该点最近的簇的质心

all_neighbours = 
[((28, 145), (25, 125)), ((65, 140), (44, 105)), ((50, 130), (25, 125)), 
 ((38, 115), (44, 105)), ((55, 118), (44, 105)), ((50, 90),  (44, 105)), 
 ((63, 88 ), (44, 105)), ((43, 83 ), (29, 97 )), ((50, 60),  (55, 63 )),
 ((50, 30 ), (55, 20 ))]
我想创建一个新列表,其中包含由这些点最近邻元组创建的新neigbourhoud/集群。类似的情况(或者用元组来分组点而不是列表):

我已尝试通过以下方式实现这一点:

centroids = set(map(lambda x: x[1], all_neighbours))
neighbourhood = [(x, [y[0] for y in all_neighbours if y[1] == x]) for x in centroids]
>>
[((55, 20), [(50, 30)]), ((25, 125), [(28, 145), (50, 130)]),
 ((44, 105), [(65, 140), (38, 115), (55, 118), (50, 90), (63, 88)]),
 ((55, 63), [(50, 60)]), ((29, 97), [(43, 83)])]
当然,这并没有产生我想要的结果。 有没有办法以一种比贝娄更为通灵的方式来完成这件事


我知道这可以通过另一次迭代来完成:

neighbourhood = [[y[0] for y in all_neighbours if y[1] == x] for x in centroids]

for neigh,cent in zip(neighbourhood, centroids):
    neigh.append(cent)
按质心对列表排序-

centroid = operator.itemgetter(1)
point = operator.itemgetter(0)

all_neighbours.sort(key = centroid)
使用
itertools.groupby
生成组

for centre, points in itertools.groupby(all_neighbours, centroid):
    print tuple([centre] + map(point, points))

neighbourhoods = [tuple([centre] + map(point, points)) for centre, points
                  in itertools.groupby(all_neighbours, centroid)]

要按质心对点进行分组,其中质心是每个元组的第1项?质心是每个元组的第2项(可以将许多点指定给同一质心)。我已经可以对它们进行分组,但无法获得所需的形式(基本上是表示邻里关系,而不是关系)。这在问题中不是很清楚吗?请发布您的示例数据的预期结果。正如您在我的问题中看到的,我已经设法产生了这个结果。例如,我希望
((25125),[(28145),(50130)]
成为
((25125),(28145),(50130))
。虽然这是一个很好的方法
centroid = operator.itemgetter(1)
point = operator.itemgetter(0)

all_neighbours.sort(key = centroid)
for centre, points in itertools.groupby(all_neighbours, centroid):
    print tuple([centre] + map(point, points))

neighbourhoods = [tuple([centre] + map(point, points)) for centre, points
                  in itertools.groupby(all_neighbours, centroid)]