Python 在列表中添加奇数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20724773/
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:06:03  来源:igfitidea点击:

Adding odd numbers in a list

python

提问by PhysicsLemur

I am trying to find the sum of all odd numbers within a given range but I cannot figure out how to specify which numbers are odd. My professor said to use "for num in numbers" to access the elements in the range. This is what I have so far.

我试图找到给定范围内所有奇数的总和,但我无法弄清楚如何指定哪些数字是奇数。我的教授说使用“for num in numbers”来访问范围内的元素。这是我到目前为止。

numbers = range(0, 10)

def addOddNumbers(numbers):
    for num in numbers:
        if num % 2 == 1:
            return sum
        print sum(numbers)

if __name__ == '__main__':
    addOddNumbers(numbers)

回答by Martijn Pieters

You were nearly there; using num % 2is the correct method to test for odd and even numbers.

你快到了;usingnum % 2是测试奇数和偶数的正确方法。

returnexits a function the moment it is executed. Your function returns when the first odd number is encountered.

return函数一执行就退出。您的函数在遇到第一个奇数时返回。

Don't use sum()if you use a loop, just add the numbers directly:

sum()如果使用循环就不要使用,直接添加数字即可:

def addOddNumbers(numbers):
    total = 0
    for num in numbers:
        if num % 2 == 1:
            total += num
    print total

You couldfirst build a list of odd numbers for sum():

可以首先为 构建一个奇数列表sum()

def addOddNumbers(numbers):
    odd = []
    for num in numbers:
        if num % 2 == 1:
            odd.append(num)
    print sum(odd)

For sum(), you can use a generator expression:

对于sum(),您可以使用生成器表达式:

def addOddNumbers(numbers):
    print sum(num for num in numbers if num % 2 == 1)

回答by heyufool1

The modulo operator "%" is what you want, and have used. However, modulo returns the remainder, so the remainder of an even number divided by 2 is 0.

模运算符“%”是您想要的,并且已经使用过。但是,取模返回余数,因此偶数除以 2 的余数为 0。

So, you want to change:

所以,你想改变:

if num % 2 == 1:

to

if num % 2 == 0:

回答by Totem

You could do this:

你可以这样做:

def addOddNumbers(numbers):
    return sum(num for num in numbers if num % 2 == 1) # or use print instead of return

To print it if you use return, you would precede the function call with the print statement:

要在使用 return 时打印它,请在函数调用之前使用 print 语句:

print addOddNumbers(numbers)

your statement return sumjust returns the sumfunction(nothing else) and exits the addOddNumbersfunction.

你的语句return sum只返回sum函数(没有别的)并退出addOddNumbers函数。

print sum(numbers)actually just prints the sum of EVERY number in numbers:

print sum(numbers)实际上只是打印数字中每个数字的总和:

you for loop if would need a variable to keep track of your total:

你 for 循环 if 需要一个变量来跟踪你的总数:

total = 0
for n in numbers:
    if n % 2 == 1:
        total += n # total accumulates the sum of all odd numbers then you can return or print it

回答by s.gray

May I suggest a small tweak to Martijn Pieter's excellent answer?

我可以建议对 Martijn Pieter 的出色回答进行一些小调整吗?

To make your method more flexible, try incorporating range into the method. It will make your method able to sum the odd values in any list. Also, I switched up your method signature so that it conforms to the Python Style Guide PEP8, just being picky here:)

为了使您的方法更加灵活,请尝试将范围合并到方法中。它将使您的方法能够对任何列表中的奇数值求和。此外,我切换了您的方法签名,使其符合 Python 风格指南PEP8,只是在这里挑剔:)

def add_odd_numbers(max_list_value):
    numbers = range(0, max_list_value)
    total = 0
    for num in numbers:
        if num % 2 == 1:
            total += num
    return total

if __name__ == '__main__':
    print add_odd_numbers(10)

回答by cdhagmann

Just to make a quick comment in the form of an answer. If you wanted to make a list of all the odd number in a between 0 and 10, the end points don't matter. If the list was from 0 to 11 then the end point matters. Just remember that range(0,11) = [0,1,2,3,4,5,6,7,8,9,10]and won't include 11.

只是为了以答案的形式快速发表评论。如果您想列出 0 到 10 之间的所有奇数,终点并不重要。如果列表是从 0 到 11,那么终点很重要。请记住这一点,range(0,11) = [0,1,2,3,4,5,6,7,8,9,10]并且不会包括 11。



Now to explain the generator that is being used. To make to list using numbersas defined by you, you could do this.

现在解释正在使用的生成器。要numbers按照您的定义使用列表,您可以这样做。

odds = []
for num in numbers:
    if num % 2 == 1:
        odds.append(num)

This would give you odds = [1,3,5,7,9]. Python has something call list comprehension that make it really easy to do things like this. The above can be easily written like this

这会给你odds = [1,3,5,7,9]。Python 有一些调用列表理解,可以很容易地做这样的事情。上面可以很容易地写成这样

odds = [num for num in number if num % 2 == 1]

and since you want the sum off all the numbers in the list and the sumfunction takes list, the answer is just

并且由于您想要列表中所有数字的总和并且sum函数需要列表,因此答案就是

sum([num for num in number if num % 2 == 1])

Note that most of the answer don't have brackets. This is because without it it becomes a generator.

请注意,大多数答案都没有括号。这是因为没有它它就变成了一个发电机。

odds = (num for num in number if num % 2 == )
print odds  #--> <generator object <genexpr> at 0x7f9d220669b0>
odds.next() # 1
odds.next() # 3
...

Since sumtakes these as well and generator are faster and less memory intensive than list that is why the best answer is

由于也sum采用这些,并且生成器比列表更快且内存占用更少,这就是为什么最好的答案是

sum(num for num in numbers if num % 2 == 1)

回答by Sham Says

I believe sum(range(1,end_number,2)will work well, and easy,.

我相信sum(range(1,end_number,2)会工作得很好,而且很容易。