可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
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.