【问题标题】:Python: Adding elements to an dict list or associative arrayPython:将元素添加到字典列表或关联数组
【发布时间】:2011-04-29 00:51:05
【问题描述】:

我试图将元素添加到 dict 列表(关联数组),但每次循环时,数组都会覆盖前一个元素。所以我最终得到一个大小为 1 的数组,最后一个元素被读取。我验证了密钥每次都在变化。

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

任何帮助都会很棒,谢谢 =]

【问题讨论】:

    标签: python list associative-array


    【解决方案1】:

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

    【讨论】:

      【解决方案2】:

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

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

      您的版本存在问题:

      1. 关联数组是 dicts 和空 dicts = {}
      2. 数组是列表,空列表 = []
      3. 您每次都将数组指向新字典。

      这就像说:

      array={result.group(1) : result.group(2)}
      array={'x':1}
      array={'y':1}
      array={'z':1}
      ....
      

      数组保持一个元素字典

      【讨论】:

      • 根据:diveintopython.org/getting_to_know_python/dictionaries.html 我应该能够按照我写的方式添加元素。我真的不明白为什么我不能按照网站中指定的方式来做。编辑:哦,我明白我做错了什么。愚蠢的我=]再次感谢
      • @nubme - 不,您的方式在循环的每次迭代中初始化 array 字典。请参阅array = ... 初始化。
      • @nubme:请参阅我的最后一部分答案。这就像说 k = 1 然后 k = 2 然后 k = 3。 K 是 3 对。而不是 1、2、3。在循环中,您每次都将数组指向新的 dict。
      • 按照你的方式,你实例化一个新的 dict 对象并替换前一个。创建对象时,{foo: bar} 语法是可以的。当你想给一个dict添加一个元素时,你必须使用dict[foo] = bar。
      【解决方案3】:
      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)
      

      【讨论】:

      • 第一个不是 OP 想要的。他想要一本字典(关联数组)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-31
      • 1970-01-01
      • 2020-09-18
      相关资源
      最近更新 更多