Python Array is read-only, can't append values

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

I am new to Python. The following code is causing an error when it attempts to append values to an array. What am I doing wrong?

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() 

Error

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)

回答1:

You are assigning to the append() function, you want instead to call .append(float(cols.group(2))).



回答2:

Do you want to append to the array?

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

Doing this: e_rcs.append = float(cols.group(2)) replaces the append method of the array e-rcs with a floating-point value. Rarely something you want to do.



回答3:

append is a method. You're trying to overwrite it instead of calling it.

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


回答4:

Try this instead:

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() 

In Python you would only use array.array when you need to control the binary layout of your storage, i.e. a plain array of bytes in RAM.

If you are going to be doing a lot of scientific data analysis, then you should have a look at the NumPy module which supports n-dimensional arrays. Think of NumPy as a replacement for FORTRAN in doing mathematics and data analysis.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!