Python:在循环中创建关联数组

10

我想从文件读取值并创建一个关联数组。我的代码看起来像这样,但是它给了我一个错误,说我不能使用非整数作为索引。

谢谢 =]

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

1
由于您的代码不完整,我们只能猜测。例如,必须在某个地方初始化myarray,否则会出现NameError错误。请包含所有相关代码。 - S.Lott
3个回答

17
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

5
Python中的关联数组被称为映射。最常见的类型是字典(dictionary)。点击这里查看更多信息。

谢谢Ignacio,但如果我事先不知道所有的值,我该如何通过循环添加它呢? - nubme
从一个空字典开始。 - Ignacio Vazquez-Abrams

1

因为数组索引应该是整数

>>> 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) 应该是一个整数或者

如果你正在使用 map,请先定义 map

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

但我想要一个关联数组,也称为哈希表或映射。 - nubme

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接