【问题标题】:Python: Create associative array in a loopPython:在循环中创建关联数组
【发布时间】:2011-04-29 00:06:07
【问题描述】:

我想创建一个关联数组,其中包含从文件中读取的值。我的代码看起来像这样,但它给了我一个错误,说我不能索引必须是整数。

谢谢=]

for line in open(file):
  x=prog.match(line)
  myarray[x.group(1)]=[x.group(2)]

【问题讨论】:

  • 由于您的代码不完整,我们不得不猜测。请包含所有相关代码。例如,myarray 必须在某处初始化,否则您会得到 NameError。请包含所有相关代码。

标签: python associative-array


【解决方案1】:
myarray = {} # Declares myarray as a dict
for line in open(file, 'r'):
    x = prog.match(line)
    myarray[x.group(1)] = [x.group(2)] # Adds a key-value pair to the dict

【讨论】:

    【解决方案2】:

    Python 中的关联数组称为映射。最常见的类型是dictionary

    【讨论】:

    • 感谢 ignacio,但如果我不提前知道所有值,我将如何通过循环添加它。
    • 从空字典开始。
    【解决方案3】:

    因为数组索引应该是整数

    >>> a = [1,2,3]
    >>> a['r'] = 3
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: list indices must be integers, not str
    >>> a[1] = 4
    >>> a
    [1, 4, 3]
    

    x.group(1) 应该是整数或

    如果您使用地图,请先定义地图

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

    【讨论】:

    • 但我想要一个关联数组,也就是哈希表或映射
    猜你喜欢
    • 2012-03-18
    • 1970-01-01
    • 1970-01-01
    • 2013-01-12
    • 1970-01-01
    • 1970-01-01
    • 2016-09-09
    • 1970-01-01
    • 2019-03-07
    相关资源
    最近更新 更多