-3

我编写了一个函数,它从外部文件中读取数据并生成列表。该程序运行良好,我有一个读入的每个文件的数字列表。但我是 python 新手,正在努力将其保存到文件中,这是我的程序和 savefile 行:

def meanarr(image, res=None):
 "costruct code which runs over a single ccd to get the means"
 a=pyfits.getdata(image).MAG_AUTO
 q=numpy.mean(a)
 s=pyfits.getdata(image).X2WIN_IMAGE
 j=numpy.mean(s)
 f=pyfits.getdata(image).Y2WIN_IMAGE
 z=numpy.mean(f)
 g=pyfits.getdata(image).XYWIN_IMAGE
 h= abs(numpy.mean(g))
 a=[q,j,z,h]
 print a
 return res


for arg in sys.argv[1:5]:
        #print arg
        s = meanarr(arg) #meanarr is my function

datafile = open('writetest.txt', 'w')
for l in meanarr(arg):
     datafile.write(l)
datafile.close() 

但我收到一个错误TypeError: 'NoneType' object is not iterable,我不确定为什么,因为我的函数确实会产生数据。有人可以帮忙吗?

4

3 回答 3

2

由于以下meanarr功能,您会收到此错误:resis always Nonefor循环需要一个可迭代的。

顺便提一句:

看起来像for以下代码中的循环:

for arg in sys.argv[1:5]:
    #print arg
    s = meanarr(arg) #meanarr is my function

是有问题的,因为s变量在每次迭代时都会被覆盖。

你可能的意思是:

s = [meanarr(arg) for arg in sys.argv[1:5]]

但是我不清楚你想在哪里使用,s因为你似乎没有在你的代码中使用它。

于 2013-05-28T21:30:21.540 回答
1

在您的meanarr函数中,您返回None的是无法迭代的!

def meanarr(image, res=None):
 "costruct code which runs over a single ccd to get the means"
 a=pyfits.getdata(image).MAG_AUTO
 q=numpy.mean(a)
 s=pyfits.getdata(image).X2WIN_IMAGE
 j=numpy.mean(s)
 f=pyfits.getdata(image).Y2WIN_IMAGE
 z=numpy.mean(f)
 g=pyfits.getdata(image).XYWIN_IMAGE
 h= abs(numpy.mean(g))
 a=[q,j,z,h]
 print a
 return res

当您调用此函数时,您没有指定res哪个获取 None 的值并按原样返回,因此会出现错误。

请参阅以下示例并尝试将其与您的代码相关联。

>>> def testFunc(test, res = None):
         test = 10
         return res

>>> type(testFunc(10))
<type 'NoneType'>
>>> type(testFunc(10, [1, 2, 3]))
<type 'list'>
于 2013-05-28T21:30:46.893 回答
1
def meanarr(image, res=None):

此时 res=None

那么在你的代码中没有任何地方,你对 res 做了什么吗

下次 res 发生任何事情时

return res

所以它返回None

所以你的代码几乎可以简化为

def meanarr():
   return None
于 2013-05-28T21:31:27.477 回答