f=open("table.txt","r")
a=[]
b=[]
mydict = {}
for line in f:
a.append(line.strip("\n"))
f.close()
length1=len(a)
for x in range(0,length1):
b.append(a[x].split("\t"))
for el in b:
if el is not None:
k=el[0].strip("")
v=el[1].strip(" ")
z=el[2].strip("\n")
if not k in mydict:
mydict[k] = {}
mydict[k][v]=float(z)
else:
mydict[k][v]=float(z)
print mydict
当我打印字典时,它看起来像这样
{'156.56.250.227 ': {'131.179.150.72': 5.60117197037},
'131.179.150.72 ': {'139.19.158.227': 5.99330687523},
'192.33.90.66 ': {'156.56.250.227': 6.74655604362},
'130.195.4.68 ': {'158.110.27.116': 6.19012498856},
'202.202.43.198 ': {'192.33.90.66': 6.02898716927},
'165.91.55.9 ': {'131.179.150.72': 5.99274086952},
'139.19.158.227 ': {'130.195.4.68': 6.90768098831}}
None
我不知道为什么我最后得到'无'。我的文字文件看起来像这样
202.202.43.198 192.33.90.66 6.02898716927
156.56.250.227 131.179.150.72 5.60117197037
156.56.250.227 202.202.43.198 6.23671293259
130.195.4.68 158.110.27.116 6.19012498856
165.91.55.9 131.179.150.72 5.99274086952
131.179.150.72 139.19.158.227 5.99330687523
192.33.90.66 156.56.250.227 6.74655604362
139.19.158.227 130.195.4.68 6.90768098831
任何线索为什么我最终得到无?有什么建议吗?
答案 0 :(得分:0)
hcwsha的评论很可能是正确答案,因为您的代码段中没有任何内容会打印None
。
现在提供一些完全不相关的内容:您的代码段是一种非常复杂且低效的编写方式:
from collections import defaultdict
d = defaultdict(dict)
with open("table.txt","r") as f:
for line in f:
line = line.strip()
if not line:
continue
k, v, z = map(str.strip, line.split("\t"))
d[k][v] = float(z)
print d