Python - 识别列表中的负数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15993583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:32:35  来源:igfitidea点击:

Python - Identify a negative number in a list

pythonlistcountidentify

提问by Michael

I need help doing a program which should recieve ten numbers and return me the number of negative integers i typed. Example: if i enter:

我需要帮助做一个程序,它应该接收十个数字并返回我输入的负整数的数量。示例:如果我输入:

1,2,-3,3,-7,5,4,-1,4,5

the program should return me 3. I dont really have a clue, so please give me a hand :) PS. Sorry for my bad english, I hope you understand

该程序应该返回我3。我真的不知道,所以请帮我一把:) PS。抱歉我的英语不好,希望你能理解

采纳答案by Gareth Latty

Break your problem down. Can you identify a way to check if a number is negative?

分解你的问题。你能找出一种方法来检查一个数字是否为负数吗?

if number < 0:
    ...

Now, we have many numbers, so we loop over them:

现在,我们有很多数字,所以我们遍历它们:

for number in numbers:
    if number < 0:
        ...

So what do we want to do? Count them. So we do so:

那么我们想要做什么呢?数一数他们。所以我们这样做:

count = 0
for number in numbers:
    if number < 0:
        count += 1

More optimally, this can be done very easily using a generator expressionand the sum()built-in:

理想的是,这可以使用生成器表达式内置的很容易地完成:sum()

>>> numbers = [1, 2, -3, 3, -7, 5, 4, -1, 4, 5]
>>> sum(1 for number in numbers if number < 0)
3

回答by squiguy

Or you could use filterto "filter" out the negatives.

或者您可以使用过滤器来“过滤”出底片。

total = len(filter(lambda x: x < 0, my_list))

total = len(filter(lambda x: x < 0, my_list))

回答by jamylak

sum(n < 0 for n in nums)

This is the most pythonic way to do it.

这是最pythonic的方式来做到这一点。