改变为

时间:2018-03-28 07:11:51

标签: python python-3.6

这是一个使用while循环的函数

def count_negative(input_list):
    count = 0
    index = 0
    while index < len(input_list):
        if input_list[index] < 0:
            count = count + 1
        index = index + 1
    return count

有人能告诉我如何使用for循环来构建这个函数吗?

def count_negative(input_list):
    count = 0
    for i in range (input_list[]):
        if i<0 :
            count += 1;
        else:
            count += 0;
    return count

输入任何列表时总是给0。

5 个答案:

答案 0 :(得分:2)

你也可以尝试使用列表理解:

def count_negative(input_list):
    return sum(1 for i in input_list if i<0)

答案 1 :(得分:1)

def count_negative(input_list):
    count = 0
    for i in input_list:
        if i<0 :
            count += 1
    print count
    return count

input_list = [1,-2,-6,4,5,9, -3, 8,-88]
count_negative(input_list)

输出 4

答案 2 :(得分:0)

范围需要列表的长度而不是input_list []

def count_negative(input_list):
    count = 0
    for i in range (len(input_list)):
        if input_list[i]<0 :
            count += 1
    return count

答案 3 :(得分:0)

range()循环中使用len()for是迭代列表的一种不好方法,因为您必须自己维护迭代器。有时它是合理的,但不是在这里。你不需要索引,你可以免费得到一个迭代器:

def count_negative(input_list):
    count = 0

    for item in input_list:
        if item < 0 :
            count += 1 
        else:                       
            count += 0

    return count

正如其他人所说,count += 0没用,但有一个案例(一个弱者)说它是一个纪录片占位符,所以我把它留了。我确实删除了尾随的分号虽然。

答案 4 :(得分:0)

def count_negative(input_list):
    count = 0
    for i in input_list:
        if i<0 :
            count += 1;
        else:
            count += 0;
    return count

尝试这个,它会给出正确的答案。现在我将成为列表的每个元素。 https://www.tutorialspoint.com/python/python_for_loop.htm