Python:在循环中创建关联数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3994345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Create associative array in a loop
提问by nubme
I want to create an associative array with values read from a file. My code looks something like this, but its giving me an error saying i can't the indicies must be ints.
我想创建一个关联数组,其中包含从文件中读取的值。我的代码看起来像这样,但它给了我一个错误,说我不能索引必须是整数。
Thanks =]
谢谢=]
for line in open(file):
x=prog.match(line)
myarray[x.group(1)]=[x.group(2)]
回答by pyfunc
Because array indices should be an integer
因为数组索引应该是整数
>>> 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) should be an integer or
x.group(1) 应该是一个整数或
if you are using map define the map first
如果您使用地图首先定义地图
myarray = {}
for line in open(file):
x=prog.match(line)
myarray[x.group(1)]=[x.group(2)]
回答by Ignacio Vazquez-Abrams
Associative arrays in Python are called mappings. The most common type is the dictionary.
Python 中的关联数组称为映射。最常见的类型是字典。
回答by Ignacio Vazquez-Abrams
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

