在 Python 中对数字列表求和

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

Sum a list of numbers in Python

pythonlistsum

提问by layo

I have a list of numbers such as [1,2,3,4,5...], and I want to calculate (1+2)/2and for the second, (2+3)/2and the third, (3+4)/2, and so on. How can I do that?

我有一个数字列表,例如[1,2,3,4,5...], 我想计算(1+2)/2第二个,(2+3)/2第三个, (3+4)/2,等等。我怎样才能做到这一点?

I would like to sum the first number with the second and divide it by 2, then sum the second with the third and divide by 2, and so on.

我想将第一个数字与第二个数字相加并除以 2,然后将第二个数字与第三个数字相加并除以 2,依此类推。

Also, how can I sum a list of numbers?

另外,我怎样才能总结一个数字列表?

a = [1, 2, 3, 4, 5, ...]

Is it:

是吗:

b = sum(a)
print b

to get one number?

得到一个号码?

This doesn't work for me.

这对我不起作用。

回答by Rafe Kettler

Sum list of numbers:

数字总和列表:

sum(list_of_nums)

Calculating half of n and n - 1 (if I have the pattern correct), using a list comprehension:

使用列表理解计算 n 和 n - 1 的一半(如果我的模式正确):

[(x + (x - 1)) / 2 for x in list_of_nums]

Sum adjacent elements, e.g. ((1 + 2) / 2) + ((2 + 3) / 2) + ... using reduceand lambdas

对相邻元素求和,例如 ((1 + 2) / 2) + ((2 + 3) / 2) + ... 使用reducelambdas

reduce(lambda x, y: (x + y) / 2, list_of_nums)

回答by Karl Knechtel

Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... etc.

问题 1:所以你想要 (element 0 + element 1) / 2, (element 1 + element 2) / 2, ... 等等。

We make two lists: one of every element except the first, and one of every element except the last. Then the averages we want are the averages of each pair taken from the two lists. We use zipto take pairs from two lists.

我们制作了两个列表:一个是除了第一个元素之外的每个元素,另一个是除了最后一个元素之外的每个元素。那么我们想要的平均值是从两个列表中取出的每一对的平均值。我们zip过去常常从两个列表中取对。

I assume you want to see decimals in the result, even though your input values are integers. By default, Python does integer division: it discards the remainder. To divide things through all the way, we need to use floating-point numbers. Fortunately, dividing an int by a float will produce a float, so we just use 2.0for our divisor instead of 2.

我假设您希望在结果中看到小数,即使您的输入值是整数。默认情况下,Python 进行整数除法:它丢弃余数。为了彻底划分事物,我们需要使用浮点数。幸运的是,将 int 除以浮点数会产生一个浮点数,因此我们只使用2.0for 我们的除数而不是2

Thus:

因此:

averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]

Question 2:

问题2:

That use of sumshould work fine. The following works:

这种使用sum应该可以正常工作。以下工作:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45

Also, you don't need to assign everything to a variable at every step along the way. print sum(a)works just fine.

此外,您不需要在整个过程中的每一步都将所有内容分配给变量。print sum(a)工作得很好。

You will have to be more specific about exactly what you wrote and how it isn't working.

您必须更具体地说明您所写的内容以及它是如何不起作用的。

回答by TartanLlama

Try using a list comprehension. Something like:

尝试使用列表理解。就像是:

new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]

回答by Jochen Ritzel

Generators are an easy way to write this:

生成器是一种简单的写法:

from __future__ import division
# ^- so that 3/2 is 1.5 not 1

def averages( lst ):
    it = iter(lst) # Get a iterator over the list
    first = next(it)
    for item in it:
        yield (first+item)/2
        first = item

print list(averages(range(1,11)))
# [1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]

回答by kevpie

In the spirit of itertools. Inspiration from the pairwise recipe.

本着 itertools 的精神。灵感来自成对食谱。

from itertools import tee, izip

def average(iterable):
    "s -> (s0,s1)/2.0, (s1,s2)/2.0, ..."
    a, b = tee(iterable)
    next(b, None)
    return ((x+y)/2.0 for x, y in izip(a, b))

Examples:

例子:

>>>list(average([1,2,3,4,5]))
[1.5, 2.5, 3.5, 4.5]
>>>list(average([1,20,31,45,56,0,0]))
[10.5, 25.5, 38.0, 50.5, 28.0, 0.0]
>>>list(average(average([1,2,3,4,5])))
[2.0, 3.0, 4.0]

回答by tzot

Using the pairwiseitertools recipe:

使用pairwiseitertools 配方

import itertools
def pairwise(iterable):
    "s -> (s0,s1), (s1,s2), (s2, s3), ..."
    a, b = itertools.tee(iterable)
    next(b, None)
    return itertools.izip(a, b)

def pair_averages(seq):
    return ( (a+b)/2 for a, b in pairwise(seq) )

回答by Michael J. Barber

Short and simple:

简短而简单:

def ave(x,y):
  return (x + y) / 2.0

map(ave, a[:-1], a[1:])

And here's how it looks:

这是它的外观:

>>> a = range(10)
>>> map(ave, a[:-1], a[1:])
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

Due to some stupidity in how Python handles a mapover two lists, you do have to truncate the list, a[:-1]. It works more as you'd expect if you use itertools.imap:

由于 Python 处理map两个以上列表的方式有些愚蠢,您必须截断列表,a[:-1]. 如果您使用,它会更像您期望的那样工作itertools.imap

>>> import itertools
>>> itertools.imap(ave, a, a[1:])
<itertools.imap object at 0x1005c3990>
>>> list(_)
[0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]

回答by Orane

I'd just use a lambda with map()

我只是将 lambda 与 map() 一起使用

a = [1,2,3,4,5,6,7,8,9,10]
b = map(lambda x, y: (x+y)/2.0, fib[:-1], fib[1:])
print b

回答by user4183543

>>> a = range(10)
>>> sum(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not callable
>>> del sum
>>> sum(a)
45

It seems that sumhas been defined in the code somewhere and overwrites the default function. So I deleted it and the problem was solved.

似乎sum已经在代码中的某处定义并覆盖了默认功能。所以我删除了它,问题就解决了。

回答by vasanth kumar

n = int(input("Enter the length of array: "))
list1 = []
for i in range(n):
    list1.append(int(input("Enter numbers: ")))
print("User inputs are", list1)

list2 = []
for j in range(0, n-1):
    list2.append((list1[j]+list1[j+1])/2)
print("result = ", list2)