你如何在python中添加一系列数字

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

How do you add a range of numbers in python

python

提问by user2803555

I have a list of odd numbers but I still need to add them:

我有一个奇数列表,但我仍然需要添加它们:

for n in range(100, 200):
   if n % 2 == 1:
       print sum([n])

采纳答案by sberry

If you are looking to sum the odd numbers in the range of 100 to 200, then the most straight forward way would be:

如果您想对 100 到 200 范围内的奇数求和,那么最直接的方法是:

sum(range(101, 200, 2))

Start at 101 (odd), go till 199 (odd) and increment by 2 so that each number is odd. For instance,

从 101(奇数)开始,一直到 199(奇数)并加 2,使每个数字都是奇数。例如,

>>> range(101, 110)
[101, 102, 103, 104, 105, 106, 107, 108, 109]

Then you can just sum them.

然后你可以把它们相加。

If you have a preexisting list of numbers then either of the two following methods should fit your need:

如果您有一个预先存在的数字列表,那么以下两种方法中的任何一种都应该适合您的需要:

>>> nums = [1, 2, 4, 5, 6, 9, 11, 15, 20, 21]
>>> sum(filter(lambda x: x % 2, nums))
62
>>> sum(num for num in nums if num % 2)
62

And this is probably what you were trying to do:

这可能就是你想要做的:

>>> total = 0
>>> for num in nums:
...     if num % 2:
...          total += num
...
>>> total
62

回答by Paul Hankin

The sum of all numbers from 1 to N (inclusive)is N * (N + 1) / 2.

从 1 到 N(含)的所有数字之和为 N * (N + 1) / 2。

def sum_all(N):
    return N * (N + 1) // 2

The sum of all even numbers from 1 to N (inclusive) is double the sum of all numbers from 1 to N//2.

从 1 到 N(含)的所有偶数之和是从 1 到 N//2 的所有数字之和的两倍。

def sum_even(N):
    return sum_all(N // 2) * 2

The sum of all odd numbers from 1 to N (inclusive) is the difference of these.

从1到N(含)的所有奇数之和就是这些的差。

def sum_odd(N):
    return sum_all(N) - sum_even(N)

Finally, the sum of all odd numbers between a and b is the sum of all odd numbers from 1 to b minus the sum of all odd numbers from 1 to a - 1.

最后,a 和 b 之间所有奇数的总和是从 1 到 b 的所有奇数之和减去从 1 到 a - 1 的所有奇数之和。

def sum_odd_range(a, b):
    return sum_odd(b) - sum_odd(a - 1)

To answer the original question:

要回答原始问题:

print sum_odd_range(100, 199)

Note that unlike solutions using sum(), these are O(1) and will be arbitrarily faster for larger inputs.

请注意,与使用 sum() 的解决方案不同,这些是 O(1) 并且对于更大的输入将任意快。