该程序将采用Binary.text中的语法规则并将其存储到字典中,其中规则为:
N = N D
N = D
D = 0
D = 1
但当前代码返回D:D = 1,N:N = D,而我想要N:N D,N:D,D:0,D:1
import sys
import string
#default length of 3
stringLength = 3
#get last argument of command line(file)
filename1 = sys.argv[-1]
#get a length from user
try:
stringLength = int(input('Length? '))
filename = input('Filename: ')
except ValueError:
print("Not a number")
#checks
print(stringLength)
print(filename)
def str2dict(filename="Binary.txt"):
result = {}
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
print(line)
result[line[0]] = line
print (result)
return result
print (str2dict("Binary.txt"))
答案 0 :(得分:2)
首先,您选择的数据结构错误。 python中的字典是一个简单的键值映射。您喜欢的是从键到多个值的映射。为此,您需要:
from collections import defaultdict
result = defaultdict(list)
接下来,你在哪里分裂' =' ?您需要这样做才能获得您正在寻找的正确密钥/值?你需要
key, value = line.split('=', 1) #Returns an array, and gets unpacked into 2 variables
将上述两者放在一起,你可以通过以下方式进行:
result = defaultdict(list)
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
print(line)
key, value = line.split('=', 1)
result[key.strip()].append(value.strip())
return result
答案 1 :(得分:1)
根据定义,词典不能有重复的键。因此,只有一个单一的D'键。但是,如果您愿意,可以在该键上存储值列表。例如:
from collections import defaultdict
# rest of your code...
result = defaultdict(list) # Use defaultdict so that an insert to an empty key creates a new list automatically
with open(filename, "r") as grammar:
#read file
lines = grammar.readlines()
count = 0
#loop through
for line in lines:
print(line)
result[line[0]].append(line)
print (result)
return result
这将导致类似:
{"D" : ["D = N D", "D = 0", "D = 1"], "N" : ["N = D"]}