[英]graph in python from a list of edges
I have a list of edges in a text file: 我在文本文件中有一个边列表:
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
.. ...
I need to turn it into a dictionary like this: 我需要将其变成这样的字典:
graph = { "a" : ["c"],
"b" : ["c", "e"],
"c" : ["a", "b", "d", "e"],
"d" : ["c"],
"e" : ["c", "b"],
"f" : []
}
my attempt so far has been: 到目前为止,我的尝试是:
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)
However, this does not work properly inasmuch i don't get a new key when this appear in the values: as an example I get: 但是,这不能正常工作,因为当出现在值中时,我没有得到新的键:例如,我得到:
'0': ["1", "2", "3"]
'1': ['637', '754', '1319', '1350', '1463', '1523']
in the '1', the "0" is missing. 在“ 1”中,缺少“ 0”。
to make it more simple. 使它更简单。 If I have a text like this
如果我有这样的文字
a b
c d
I should get an outcome like: graph = { "a": ["b"], "b": ["a"], "c": ["d"], "d": ["c"]} 我应该得到如下结果:graph = {“ a”:[“ b”],“ b”:[“ a”],“ c”:[“ d”],“ d”:[“ c”]}
thank you in advance 先感谢您
If you want a bidirectional graph, you need two appends. 如果需要双向图,则需要两个追加。
Also, you don't really need the for key in d.keys()
loop, just append to d[row[0]]
instead of d[key]
. 另外,您实际上并不需要
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])
Also, consider using a defaultdict, in which case you wouldn't need to initialize d
with np.unique
. 另外,考虑使用defaultdict,在这种情况下,您无需使用
np.unique
初始化d
。 It will also guard against errors that would otherwise occur when a node only appears in the second column. 它还将防止当节点仅出现在第二列中时可能发生的错误。
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.