Python:向dict列表或关联数组添加元素

2024-06-06 12:54:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将元素添加到dict列表(关联数组),但每次循环时,数组都会覆盖上一个元素。所以我最后得到一个1大小的数组,最后一个元素被读取。我确认钥匙每次都在换。

array=[]
for line in open(file):
  result=prog.match(line)
  array={result.group(1) : result.group(2)}

任何帮助都很好,谢谢


Tags: in元素列表formatchlinegroup数组
3条回答

您的解决方案不正确;正确的版本是:

array={}
for line in open(file):
  result=prog.match(line)
  array[result.group(1)] = result.group(2)

版本问题:

  1. 关联数组是dict和空dict={}
  2. 数组是list,空list=[]
  3. 你每次都把数组指向新字典。

这就像是在说:

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)})

或:

array={}
for line in open(file):
  result=prog.match(line)
  array[result.group(1)] = result.group(2)

也许更像是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)

相关问题 更多 >