2009-10-30 19 views
3

我是Python新手。以下代碼在嘗試將值附加到數組時導致錯誤。我究竟做錯了什麼?Python數組是隻讀的,不能附加值

import re 
from array import array 

freq_pattern = re.compile("Frequency of Incident[\(\)A-Za-z\s]*\.*\s*([\.0-9]*)") 
col_pattern = re.compile("([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)") 
e_rcs = array('f') 

f = open('example.4.out', 'r') 

for line in f: 
    print line, 

    result = freq_pattern.search(line) 
    if result: 
     freq = float(result.group(1)) 

    cols = col_pattern.search(line) 
    if cols: 
     e_rcs.append = float(cols.group(2)) 

f.close() 

錯誤

Traceback (most recent call last):
File "D:\workspace\CATS Parser\cats-post.py", line 31, in e_rcs.append = float(cols.group(2)) AttributeError: 'list' object attribute 'append' is read-only attributes (assign to .append)

回答

6

您分配給追加()函數,你想,而不是調用.append(浮點(cols.group(2)))。

+0

當然,愚蠢的錯誤,謝謝。 – 2009-10-30 18:22:36

6

是否要追加到數組?

e_rcs.append(float(cols.group(2))) 

這樣做:e_rcs.append = float(cols.group(2))替換陣列e-rcs的具有浮點值的append方法。很少有你想要做的事情。

+2

他沒有調用數組的列表。他使用的是Python標準庫中數組模塊的數組。 – jamessan 2009-10-30 18:12:55

+0

我有n個漂浮物來存放。傳統上我會使用其他語言的數組。這就是我在Python中嘗試使用並沒有取得什麼成就。我應該在Python中使用哪種數據類型? – 2009-10-30 18:15:08

+0

@Jared Brown:numpy數組很好。有些人在使用內置的「列表」類型時會說「數組」。我在開始時未能讀取numpy數組部分。 – 2009-10-30 18:17:16

3

附加是一種方法。你試圖覆蓋它而不是調用它。

e_rcs.append(float(cols.group(2))) 
0

試試這個:

import re 

freq_pattern = re.compile("Frequency of Incident[\(\)A-Za-z\s]*\.*\s*([\.0-9]*)") 
col_pattern = re.compile("([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)\s+([-\.0-9]+)") 
e_rcs = [] # make an empty list 

f = open('example.4.out', 'r') 

for line in f: 
    print line, 

    result = freq_pattern.search(line) 
    if result: 
     freq = float(result.group(1)) 

    cols = col_pattern.search(line) 
    if cols: 
     e_rcs.append(float(cols.group(2))) # add another float to the list 

f.close() 

在Python當你需要控制你的存儲的二進制佈局,即在RAM中的字節數組平原你只會用array.array。

如果您打算進行大量的科學數據分析,那麼您應該查看支持n維數組的NumPy模塊。將NumPy視爲FORTRAN在數學和數據分析中的替代品。