我试图将元素添加到字典列表(关联数组),但每次循环时,数组都会覆盖前一个元素。所以我最终得到一个大小为1的数组,最后一个元素被读取。我确认钥匙每次都在变化。
array=[]
for line in open(file):
result=prog.match(line)
array={result.group(1) : result.group(2)}
任何帮助都会很棒,谢谢=]
答案 0 :(得分:6)
您的解决方案不正确;正确的版本是:
array={}
for line in open(file):
result=prog.match(line)
array[result.group(1)] = result.group(2)
您的版本问题:
这就像说:
array={result.group(1) : result.group(2)}
array={'x':1}
array={'y':1}
array={'z':1}
....
数组仍然是一个元素dict
答案 1 :(得分:0)
array=[]
for line in open(file):
result=prog.match(line)
array.append({result.group(1) : result.group(2)})
或者:
array={}
for line in open(file):
result=prog.match(line)
array[result.group(1)] = result.group(2)
答案 2 :(得分:0)
也许更多Pythonic:
with open(filename, 'r') as f:
array = dict(prog.match(line).groups() for line in f)
或者,如果您的prog
匹配更多群组:
with open(filename, 'r') as f:
array = dict(prog.match(line).groups()[:2] for line in f)