2010-10-22 64 views
9

我想創建一個從文件中讀取值的關聯數組。我的代碼看起來像這樣,但它給了我一個錯誤,說我不能指示必須是整數。Python:在循環中創建關聯數組

由於=]

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

由於您的代碼不完整,我們必須猜測。請包括**所有**的相關代碼。例如,'myarray'必須在某處進行初始化,否則會得到一個NameError。請包括**所有**的相關代碼。 – 2010-10-22 11:04:19

回答

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)應該是一個整數或

如果正在使用地圖定義地圖第一

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

但我想要一個關聯數組,哈希表或映射 – nubme 2010-10-22 06:18:16

+0

@nubme:得到它並編輯了我的回覆 – pyfunc 2010-10-22 06:21:48

4

Python中的關聯數組稱爲映射。最常見的類型是dictionary

+0

感謝ignacio,但是如何通過循環將其添加,如果我不提前知道所有值。 – nubme 2010-10-22 06:19:41

+0

從空字典開始。 – 2010-10-22 06:20:17

+0

納米了。謝謝=] – nubme 2010-10-22 06:21:26

12
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