python - 编写一个Python代码来计算每个列表中的负数?

标签 python list

我正在尝试创建一个 def count_neg() 函数来计算每个列表中的负数?像这样:

>>> count_neg ([[0, -1], [-2,-4],[5,5],[4,-4]])
[1,2,0,1]

我尝试制作它并想出了这个,但输出并未计入每个列表?

def count_neg(*args):
    for i in args:
        counter = 0
        for j in i:
            if j < 0:
                counter += 1 
    print(counter)

count_neg([3,-2,0],[-1,-4,3])

最佳答案

这是因为在错误的位置打印了计数器。它应该位于外循环内部而不是函数末尾。

def count_neg(*args):
    for i in args:
        counter = 0
        for j in i:
            if j < 0:
                counter += 1 
        print(counter)

count_neg([0, -1], [-2,-4], [5,5], [4,-4])

输出

1
2
0
1

关于python - 编写一个Python代码来计算每个列表中的负数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59464660/

相关文章:

python - 从读取 csv 转换为 excel - pandas/python

python - wxpython 防止Ctrl+Enter改变焦点

Python block 键盘/鼠标输入

python:分散不显示

python - 根据 python 中的值分隔列表

python - 不使用 collection.deque 旋转列表

python - 在python中找到两个二维数组之间的区别

list - 删除列表中的重复对

python - 字符串格式 : Iterate the row values from a csv file

python - Python 中是否可以增加列表的一部分?