为什么我的函数打印正确的结果,但返回NONE?

时间:2013-01-23 03:24:27

标签: python return

通常,我的代码只会检查match1中的值是否大于某个值,并返回符合此条件的第一对值。

list1 = []
list2 = []
list3 = []
match1 = []
match2 = []

def readmod(infile): 
    with open(infile, 'rb') as csvfile1:                       
        datain = csv.reader(csvfile1, delimiter=',')
        for line in datain:
            if "#" not in line[0]:
                list1.append(float(line[3]))
                list2.append(float(line[4]))
                list3.append(float(line[5]))

def findall(value):
    for i in numpy.arange(len(list1)):
        if value == list1[i]:
            match1.append(list2[i])
            match2.append(list3[i])

def check(threshold = 1.0):
    for i in numpy.arange(len(match1)):
        if match1[i] >= threshold:
            print match1[i], match2[i]
            return match1[i], match2[i]
        elif i+1 == len(match1):
            print match1[0], match2[0]
            return match1[0], match2[0]


testinfile = mock.csv
testvalue = 1.3
readmod(testinfile)
findall(testvalue)
result = check()
print result

但是,当我运行代码时,该函数会输出正确的值,例如。 1.1,3.1。但它返回NONE

编辑:很抱歉回答之前的回复,我只是为这篇文章编辑了我的变量名,所以“Threshold”应该实际上是“阈值”。当然,我上传了更多带有更改变量名称的代码。所以列表是从csv读入的,匹配列表是正确的,但check()仍然返回NONE

result = check()
print result

它返回NONE

2 个答案:

答案 0 :(得分:1)

我相信,如果上面的代码是你正在运行而没有获得'Threshold'的NameError,那么你很可能在全局级别定义了这个变量,导致它以不合需要的方式运行。

正如其他人在评论中已经提到的那样,将行if match1[i] >= Threshold:更改为if match1[i] >= threshold:

另外,为了完成答案,我发布了一个更好的itertools解决方案

>>> from itertools import izip
>>> next(e for e in izip(match1, match2) if e[0] > 1.0)
(1.1, 3.1)

答案 1 :(得分:0)

在这里工作正常。 虽然从您的代码中,我没有看到您实际上调用您的函数。因此,如果你按原样运行那段代码,它将定义2个变量并且实际上没有返回。