首页 > 解决方案 > 从元组中提取边集

问题描述

我创建了以下程序。它需要一个输入 G,它由图的顶点以及边和相应的边权重组成。该程序的目的是仅提取边缘

def edges(G):     
    E =[]     
    for i in G[1]:         
        E.append(i[0])     
    return E  
print (edges(G))

在以下输入

G = [({'a', 'b'}, 4), ({'a', 'c'}, 6), ({'a', 'd'}, 8), ({'b', 'e'}, 1) ,
      ({'b', 'f'}, 9), ({'c', 'f'}, 3), ({'d', 'g'}, 7), ({'d', 'h'}, 0)]

产生以下输出:

[{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'e', 'b'}, {'f', 'b'}, {'f', 'c'}, {'g', 'd'}, {'h', 'd'}]

我想要得到的输出是:

[{'a', 'b'}, {'a', 'c'}, {'a', 'd'}, {'b', 'e'}, {'b', 'f'}, {'c', 'f'}, {'d', 'g'}, {'d', 'h'}]

谁能解释为什么我提取的元组被重新排序?

标签: pythonlistsortinggraphkruskals-algorithm

解决方案


Aset是一个无序集合。你所要求的是不可能的。

您可以做的最好的事情是使用有序集合,例如listor tuple。下面是一个例子。

res = [tuple(sorted(x[0])) for x in G]

print(res)

[('a', 'b'), ('a', 'c'), ('a', 'd'), ('b', 'e'),
 ('b', 'f'), ('c', 'f'), ('d', 'g'), ('d', 'h')]

这在功能上也是可能的,但由于 Python 没有本机函数组合,所以很麻烦。对于组合,您可以使用 3rd party library toolz

from operator import itemgetter
from toolz import compose

res = list(map(compose(tuple, sorted, itemgetter(0)), G))

推荐阅读