2024-06-06 12:54:19 发布
网友
我试图将元素添加到dict列表(关联数组),但每次循环时,数组都会覆盖上一个元素。所以我最后得到一个1大小的数组,最后一个元素被读取。我确认钥匙每次都在换。
array=[] for line in open(file): result=prog.match(line) array={result.group(1) : result.group(2)}
任何帮助都很好,谢谢
您的解决方案不正确;正确的版本是:
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
array=[] for line in open(file): result=prog.match(line) array.append({result.group(1) : result.group(2)})
或:
也许更像是Python:
with open(filename, 'r') as f: array = dict(prog.match(line).groups() for line in f)
或者,如果您的prog与更多组匹配:
prog
with open(filename, 'r') as f: array = dict(prog.match(line).groups()[:2] for line in f)
您的解决方案不正确;正确的版本是:
版本问题:
这就像是在说:
数组保留一个元素dict
或:
也许更像是Python:
或者,如果您的
prog
与更多组匹配:相关问题 更多 >
编程相关推荐