在 python 中插入图形时处理索引
handling indices when inserting a graph in python
考虑以下列表:
["abc", "abx", "axx", "abx", "abc"]
现在将列表中的每个元素视为 graph.Two 的顶点,如果两个元素仅在一个字符上不同,则顶点相连:
abc > abx
abc > abx
ans 所以 on.So 最终结果将是:
{"0":["1","3"],"1":["0","2","4"],"2":["1","3"],"3":["0","3","4"],"4":["1","3"]}
这些数字是 indices.I 已经做了一个函数来检查是否
顶点应该是连接的(它 returns 布尔值)但主要问题是当列表中有多个元素时(在我的例子中有两个 "abc" 和两个 "abx")。这个问题是当我想自动找到 "abc".Python 之类的索引和元素时 returns 较小的索引(即 0)但是当比较 "abx" 与"abc" 两个索引(0 和 3)都是 important.It 变得糟糕,因为应该检查 C(5,2) = 10 对。
我想我应该以某种方式告诉 python 检查每个元素是否不止一个,并记住它使用了多少次 them.I 真的不知道如何进一步发展这个想法(也它是否有用)以及如何在代码中执行它。
感谢您的关注。
您可以执行以下操作:
from itertools import combinations as comb
from collections import defaultdict
# a,b are strings from the list, i,j are their respective indexes
edges = [(i,j) for (i,a),(j,b) in comb(enumerate(lst), 2) if len(set(a)-set(b))==1]
# [(0, 1), (0, 3), (1, 2), (1, 4), (2, 3), (3, 4)]
dd = defaultdict(list)
for i, j in edges:
dd[i].append(j)
dd[j].append(i)
# {0: [1, 3], 1: [0, 2, 4], 2: [1, 3], 3: [0, 2, 4], 4: [1, 3]}
这使用 enumerate
to get the indexes, itertools.combinations
to get all possible pairs. Set difference is utilised in the conditional comprehension to filter out all the pairings differing in exactly 1 letter and a collections.defaultdict
方便地从这些边缘构建最终数据结构。
考虑以下列表:
["abc", "abx", "axx", "abx", "abc"]
现在将列表中的每个元素视为 graph.Two 的顶点,如果两个元素仅在一个字符上不同,则顶点相连:
abc > abx
abc > abx
ans 所以 on.So 最终结果将是:
{"0":["1","3"],"1":["0","2","4"],"2":["1","3"],"3":["0","3","4"],"4":["1","3"]}
这些数字是 indices.I 已经做了一个函数来检查是否
顶点应该是连接的(它 returns 布尔值)但主要问题是当列表中有多个元素时(在我的例子中有两个 "abc" 和两个 "abx")。这个问题是当我想自动找到 "abc".Python 之类的索引和元素时 returns 较小的索引(即 0)但是当比较 "abx" 与"abc" 两个索引(0 和 3)都是 important.It 变得糟糕,因为应该检查 C(5,2) = 10 对。
我想我应该以某种方式告诉 python 检查每个元素是否不止一个,并记住它使用了多少次 them.I 真的不知道如何进一步发展这个想法(也它是否有用)以及如何在代码中执行它。
感谢您的关注。
您可以执行以下操作:
from itertools import combinations as comb
from collections import defaultdict
# a,b are strings from the list, i,j are their respective indexes
edges = [(i,j) for (i,a),(j,b) in comb(enumerate(lst), 2) if len(set(a)-set(b))==1]
# [(0, 1), (0, 3), (1, 2), (1, 4), (2, 3), (3, 4)]
dd = defaultdict(list)
for i, j in edges:
dd[i].append(j)
dd[j].append(i)
# {0: [1, 3], 1: [0, 2, 4], 2: [1, 3], 3: [0, 2, 4], 4: [1, 3]}
这使用 enumerate
to get the indexes, itertools.combinations
to get all possible pairs. Set difference is utilised in the conditional comprehension to filter out all the pairings differing in exactly 1 letter and a collections.defaultdict
方便地从这些边缘构建最终数据结构。