Python: 向字典列表或关联数组添加元素
我正在尝试往一个字典列表(关联数组)里添加元素,但每次循环的时候,数组都会覆盖掉之前的元素。结果我最后只得到一个大小为1的数组,里面只有最后一个读取的元素。我确认每次的键确实是不同的。
array=[]
for line in open(file):
result=prog.match(line)
array={result.group(1) : result.group(2)}
如果能帮忙就太好了,谢谢!=]
3 个回答
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)
0
也许这样写会更符合Python的风格:
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)
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}
....
数组始终只包含一个元素的字典。