python - 从元组中提取边集

标签 python list sorting graph kruskals-algorithm

我创建了以下程序。它需要一个输入 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 .您所要求的是不可能的。

您最好的办法是使用有序集合,例如listtuple。下面是一个例子。

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/

相关文章:

c# - 如何编辑列表中的重复项?

c - 是否可以将 strcpy 与单字符变量一起使用?

java - 按值对 Map<Key, Value> 进行排序

python - 如何将单选按钮添加到 Tkinter 中的子菜单

python - ASP.NET 成员(member)资格的开源替代方案

python - 将模型从 pytorch 转换为 ONNX 后获得不同的结果

python - 反转python中列表列表中的元素

java - java 8中如何将列表值与另一个列表的索引值进行比较?

c# - 在 c# 中根据其子元素对 arraylist 进行排序

python - 在 python numpy 中创建动态数组名称