[英]Loading data from a list of lists (representing edges) into an igraph graph in python
[英]graph in python from a list of edges
我在文本文件中有一个边列表:
0 1
0 2
0 3
1 637
1 754
1 1319
1 1350
1 1463
1 1523
2 637
2 754
2 1319
2 1350
2 1463
2 1523
3 499
3 539
3 595
3 637
3 706
3 1128
3 1194
3 1213
3 1319
.. ...
我需要将其变成这样的字典:
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
到目前为止,我的尝试是:
import numpy as np
file_name='/Volumes/City_University/data_mining/Ecoli.txt'
key_column=0
dat=np.genfromtxt(file_name,dtype=str)
d={i:[] for i in np.unique(dat[:,key_column])}
for row in dat:
for key in d.keys():
if row[key_column]==key :d[key].append(row[1])
print (d)
但是,这不能正常工作,因为当出现在值中时,我没有得到新的键:例如,我得到:
'0': ["1", "2", "3"]
'1': ['637', '754', '1319', '1350', '1463', '1523']
在“ 1”中,缺少“ 0”。
使它更简单。 如果我有这样的文字
a b
c d
我应该得到如下结果:graph = {“ a”:[“ b”],“ b”:[“ a”],“ c”:[“ d”],“ d”:[“ c”]}
先感谢您
如果需要双向图,则需要两个追加。
另外,您实际上并不需要for key in d.keys()
循环中的for key in d.keys()
,只需追加到d[row[0]]
而不是d[key]
。
for row in dat:
d[row[0]].append(row[1])
d[row[1]].append(row[0])
另外,考虑使用defaultdict,在这种情况下,您无需使用np.unique
初始化d
。 它还将防止当节点仅出现在第二列中时可能发生的错误。
import numpy as np
from collections import defaultdict
file_name='/Volumes/City_University/data_mining/Ecoli.txt'
dat=np.genfromtxt(file_name,dtype=str)
d=defaultdict(list)
for row in dat:
d[row[0]].append(row[1])
d[row[1]].append(row[0])
print (d)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.