我创建了以下程序。它需要一个输入 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'}]
谁能解释为什么我提取的元组被重新排序?
最佳答案
一个 set
是一个 unordered collection .您所要求的是不可能的。
您最好的办法是使用有序集合,例如list
或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 没有原生函数组合,所以很麻烦。对于组合,您可以使用第 3 方库 toolz
.
from operator import itemgetter
from toolz import compose
res = list(map(compose(tuple, sorted, itemgetter(0)), G))
关于python - 从元组中提取边集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50075383/