[英]Python - Read a complicated file into dictionary
我的輸入文件是:
-150 150 -90 130 1
-150 150 -150 170 1
-150 150 -110 140 1
-150 160 -80 -20 1
-150 170 -140 160 1
-150 170 -70 -40 1
-140 -170 -110 150 1
-140 130 -120 110 1
-140 140 160 -150 1
-140 160 -150 150 1
我需要創建一個 python 字典,使得鍵是前兩列,值是另一個字典,其中鍵是 3+4 列,值是第 5 列:
'-140 160' : {'-150 150' : 0.0188679245283019},
'-140 -170' : {'-110 150' : 0.0188679245283019},
'-150 170' : {'-140 160' : 0.0188679245283019, '-70 -40' : 0.0188679245283019},
'-150 160' : {'-80 -20' : 0.0188679245283019},
'-150 150' : {'-150 170' : 0.0188679245283019, '-110 140' : 0.0188679245283019}
到目前為止,我一直在使用 perl 腳本將其轉換為類似於我上面顯示的文本,然后將該文本復制粘貼到我的 python 代碼中。 (這個值變成了分數,因為我將它除以總和,即 56
from collections import defaultdict
bigdict = defaultdict(dict)
for ln in file:
a,b,c,d,e = ln.split()
bigdict[(a,b)][(c,d)] = e
如果您想要字符串鍵,請將(a,b)
替換為'%s %s' % (a, b)
並類似地替換(c,d)
。
這應該有效:
f = open('file')
dictionary = {}
for line in f:
a, b, c, d, e = line.split()
try:
dictionary['%s %s' % (a, b)]['%s %s' % (c, d)] = e
except KeyError:
dictionary['%s %s' % (a, b)] = dict([('%s %s' % (c, d), e)])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.