0

我怎样才能使功能。显示所有不好的值,而不仅仅是一个?

def get_bad_results(person_results):
        for i in person_results:
                if i[1]>i[3] or i[1]<i[2]:
                    return i[0]

test_results = [["White blood cells",8.5,2,7],
                ["Neutrophils",5.3,2.5,5],
                ["Red blood cells", 12.4, 9,15]]

a = get_bad_results(test_results)
print a

显示White blood cells

代替

White blood cells, Neutrophils
4

5 回答 5

5

您的count_healthy()函数没有returnbNone. 由于该函数执行打印,然后是print b,这解释了 aNone在函数输出之后的输出。

基本上,一个应该进行计数的函数可能不应该打印结果,而是应该打印结果,return以便调用者可以决定应该打印或以不同方式处理结果。

于 2012-11-09T13:03:15.533 回答
1

您的函数没有return语句,因此它隐式返回None.

尝试添加return语句并返回要打印的值。

于 2012-11-09T13:03:29.017 回答
1

正如您期望每次调用有多个结果一样,最好使用生成器函数:

def get_bad_results(person_results):
    for i in person_results:
        if i[1]>i[3] or i[1]<i[2]:
            yield i[0]

或生成器表达式:

def get_bad_results(person_results):
    return (i[0] for i in person_results if i[1]>i[3] or i[1]<i[2])

以便

test_results = [["White blood cells",8.5,2,7],
                ["Neutrophils",5.3,2.5,5],
                ["Red blood cells", 12.4, 9,15]]

for i in get_bad_results(test_results):
    print i
print list(get_bad_results(test_results))
print ", ".join(get_bad_results(test_results))

给出输出

White blood cells
Neutrophils
['White blood cells', 'Neutrophils']
White blood cells, Neutrophils

对于其他功能,请执行

def count_healthy(all_results):
    counter = 0
    for i in all_results:
        if len(list(get_bad_results(i))) == 0:
            counter += 1
    return counter

要不就

def count_healthy(all_results):
    return sum(1 for i in all_results if len(list(get_bad_results(i))) == 0)

编辑:

对于许多人来说get_bad_results(),将其转换为列表可能会占用大量内存。

所以len(list(get_bad_results(i))) == 0你可以使用

def has_results(it):
    """Returns True if the iterator it yields any items."""
    return next((True for _ in it), False)

进而

def count_healthy(all_results):
    return sum(1 for i in all_results if not has_results(get_bad_results(i)))
于 2012-11-09T14:03:35.197 回答
0

您正在尝试打印函数的结果

a = get_bad_results(test_results)
print a

b =count_healthy(all_results)
print b

默认情况下,函数返回 None

于 2012-11-09T13:02:55.587 回答
0

好的,我修好了,但现在

def get_bad_results(person_results):
        for i in person_results:
                if i[1]>i[3] or i[1]<i[2]:
                    return i[0]

test_results = [["White blood cells",8.5,2,7],
                ["Neutrophils",5.3,2.5,5],
                ["Red blood cells", 12.4, 9,15]]

a = get_bad_results(test_results)
print a

显示White blood cells

代替White blood cells, Neutrophils

于 2012-11-09T13:33:48.433 回答