我正在尝试为python中的网络可视化构建一个Pajek NET文件。我的方法是使用一个二维列表或dict作为第二个的键,并替换值或完全创建一个新列表。示例输入:
Vertices = [('1', 'test.com'), ('2', 'testb.com'), ('3', 'testc.com'), ('4', '1.1.1.1'), ('5', '2.2.2.2'), ('6', '3.3.3.3')]
matches = [('test.com', '1.1.1.1'), ('test.com', '3.3.3.3'), ('test.com', '2.2.2.2'), ('testb.com', '3.3.3.3'), ('testc.com', '3.3.3.3')]
结果,将匹配中的k和v替换为顶点中的k。输出列表如此呈现
Edges = [('1', '4'), ('1', '6'), ('1', '5'), ('2', 6'), ('3', '6')]
不确定如何解决这个问题。欣赏大师的任何见解
答案 0 :(得分:2)
如果您选择了不同的数据结构,那将是微不足道的:
>>> Vertices = {'test.com': '1', 'testb.com': '2', 'testc.com': '3', '1.1.1.1': '4', '2.2.2.2': '5', '3.3.3.3': '6'}
>>> matches = [('test.com', '1.1.1.1'), ('test.com', '3.3.3.3'), ('test.com', '2.2.2.2'), ('testb.com', '3.3.3.3'), ('testc.com', '3.3.3.3')]
>>> Edges = [(Vertices[v1], Vertices[v2]) for v1,v2 in matches]
>>> Edges
[('1', '4'), ('1', '6'), ('1', '5'), ('2', '6'), ('3', '6')]
使用您自己的数据结构,它会变得错综复杂:
>>> Edges = []
>>> for item in matches:
... for vertex in Vertices:
... if vertex[1] == item[0]:
... i = vertex[0]
... break
... for vertex in Vertices:
... if vertex[1] == item[1]:
... j = vertex[0]
... break
... Edges.append((i,j))
...
>>> Edges
[('1', '4'), ('1', '6'), ('1', '5'), ('2', '6'), ('3', '6')]