python - 从元组中提取边集
问题描述
我创建了以下程序。它需要一个输入 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'}]
谁能解释为什么我提取的元组被重新排序?
解决方案
Aset
是一个无序集合。你所要求的是不可能的。
您可以做的最好的事情是使用有序集合,例如list
or 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))
推荐阅读
- javascript - 在 firebase 函数中读取 CSV 文件时遇到问题
- php - 如何获取背包杂物列的数字索引值?
- recursion - 使用 Spectre 递归地改变地图中的值
- python - 在python中以最短时间查找列表的所有子列表
- android - 在 Firebase for Android 中验证电话号码而不发送短信
- ocaml - 在 wsl 上使用沙丘时,ctypes 被隐藏(不满足“exist_if”)错误
- c++ - 静态成员函数内部的局部静态变量在内存中的什么位置?
- r - 如何从 Choroplethr 地图中删除州缩写
- android - 如何将应用程序的图标与第一个活动的图标分开?
- python - 如何在我的价值表数字前面放一个 $