问题:对Python中的数字列表求和
我有一个数字列表,例如[1,2,3,4,5...]
,我想计算(1+2)/2
第二个,(2+3)/2
第三个,
(3+4)/2
等等。我怎样才能做到这一点?
我想将第一个数字与第二个数字相加并除以2,然后将第二个数字与第三个数字相加并除以2,依此类推。
另外,如何求和数字列表?
a = [1, 2, 3, 4, 5, ...]
是吗:
b = sum(a)
print b
得到一个号码?
这对我不起作用。
I have a list of numbers such as [1,2,3,4,5...]
, and I want to calculate (1+2)/2
and for the second, (2+3)/2
and the third,
(3+4)/2
, and so on. How can I do that?
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.
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.
回答 0
问题1:因此,您想要(元素0 +元素1)/ 2,(元素1 +元素2)/ 2,…等等。
我们列出两个列表:除第一个元素之外的每个元素中的一个,除最后一个元素之外的每个元素中的一个。然后,我们想要的平均值是从两个列表中得出的每对平均值。我们zip
过去常常从两个列表中取对。
我假设即使输入值是整数,您也希望在结果中看到小数。默认情况下,Python会进行整数除法:它会丢弃余数。要完全划分事物,我们需要使用浮点数。幸运的是,将int除以浮点数将产生一个浮点数,因此我们仅将其2.0
用作除数而不是2
。
从而:
averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]
问题2:
的使用sum
应该可以正常工作。以下作品:
a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45
同样,您不需要在此过程的每一步都将所有内容分配给变量。print sum(a)
效果很好。
您将必须更确切地确切地写出您所写的内容以及它是如何工作的。
Question 1: So you want (element 0 + element 1) / 2, (element 1 + element 2) / 2, … etc.
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 zip
to take pairs from two lists.
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.0
for our divisor instead of 2
.
Thus:
averages = [(x + y) / 2.0 for (x, y) in zip(my_list[:-1], my_list[1:])]
Question 2:
That use of sum
should work fine. The following works:
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.
You will have to be more specific about exactly what you wrote and how it isn’t working.
回答 1
总数列表:
sum(list_of_nums)
使用列表推导计算n和n-1的一半(如果我的模式正确):
[(x + (x - 1)) / 2 for x in list_of_nums]
对相邻元素求和,例如((1 + 2)/ 2)+((2 + 3)/ 2)+ …使用reduce和lambda
reduce(lambda x, y: (x + y) / 2, list_of_nums)
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:
[(x + (x - 1)) / 2 for x in list_of_nums]
Sum adjacent elements, e.g. ((1 + 2) / 2) + ((2 + 3) / 2) + … using reduce and lambdas
reduce(lambda x, y: (x + y) / 2, list_of_nums)
回答 2
问题2:
总结一个整数列表:
a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18
如果列表包含整数作为字符串:
a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)
Question 2:
To sum a list of integers:
a = [2, 3, 5, 8]
sum(a)
# 18
# or you can do:
sum(i for i in a)
# 18
If the list contains integers as strings:
a = ['5', '6']
# import Decimal: from decimal import Decimal
sum(Decimal(i) for i in a)
回答 3
您可以这样尝试:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm # Python 2
You can try this way:
a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
sm = sum(a[0:len(a)]) # Sum of 'a' from 0 index to 9 index. sum(a) == sum(a[0:len(a)]
print(sm) # Python 3
print sm # Python 2
回答 4
>>> 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
似乎sum
已经在代码中的某个地方定义了该代码,并覆盖了默认功能。所以我删除了它,问题解决了。
>>> 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 sum
has been defined in the code somewhere and overwrites the default function. So I deleted it and the problem was solved.
回答 5
使用简单list-comprehension
和sum
:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
Using a simple list-comprehension
and the sum
:
>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5
回答 6
所有答案均显示出程序化和通用的方法。我建议针对您的情况的数学方法。特别是对于长列表,它可能会更快。之所以有效,是因为您的列表是一个自然数列表,最多可包含n
:
假设我们有自然数1, 2, 3, ..., 10
:
>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
您可以sum
在列表中使用该功能:
>>> print sum(nat_seq)
55
您还可以使用公式n*(n+1)/2
where n
是列表中最后一个元素的值(此处nat_seq[-1]
:),因此可以避免迭代元素:
>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55
要生成序列(1+2)/2, (2+3)/2, ..., (9+10)/2
,可以使用生成器和公式(2*k-1)/2.
(注意点使值成为浮点)。生成新列表时,您必须跳过第一个元素:
>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
您也可以sum
在此列表中使用该函数:
>>> print sum(new_seq)
49.5
但是您也可以使用公式(((n*2+1)/2)**2-1)/2
,因此可以避免迭代元素:
>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5
All answers did show a programmatic and general approach. I suggest a mathematical approach specific for your case. It can be faster in particular for long lists. It works because your list is a list of natural numbers up to n
:
Let’s assume we have the natural numbers 1, 2, 3, ..., 10
:
>>> nat_seq = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
You can use the sum
function on a list:
>>> print sum(nat_seq)
55
You can also use the formula n*(n+1)/2
where n
is the value of the last element in the list (here: nat_seq[-1]
), so you avoid iterating over elements:
>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55
To generate the sequence (1+2)/2, (2+3)/2, ..., (9+10)/2
you can use a generator and the formula (2*k-1)/2.
(note the dot to make the values floating points). You have to skip the first element when generating the new list:
>>> new_seq = [(2*k-1)/2. for k in nat_seq[1:]]
>>> print new_seq
[1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5, 9.5]
Here too, you can use the sum
function on that list:
>>> print sum(new_seq)
49.5
But you can also use the formula (((n*2+1)/2)**2-1)/2
, so you can avoid iterating over elements:
>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5
回答 7
解决此问题的最简单方法:
l =[1,2,3,4,5]
sum=0
for element in l:
sum+=element
print sum
The simplest way to solve this problem:
l =[1,2,3,4,5]
sum=0
for element in l:
sum+=element
print sum
回答 8
这个问题已经在这里回答
a = [1,2,3,4] sum(a)返回10
This question has been answered here
a = [1,2,3,4]
sum(a) returns 10
回答 9
import numpy as np
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]
import numpy as np
x = [1,2,3,4,5]
[(np.mean((x[i],x[i+1]))) for i in range(len(x)-1)]
# [1.5, 2.5, 3.5, 4.5]
回答 10
生成器是编写此代码的简单方法:
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]
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]
回答 11
让我们为初学者轻松:-
- 的
global
关键字将允许主函数内分配全局变量消息,而不产生新的本地变量
message = "This is a global!"
def main():
global message
message = "This is a local"
print(message)
main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope
这个概念叫做阴影
- 对Python中的数字列表求和
nums = [1, 2, 3, 4, 5]
var = 0
def sums():
for num in nums:
global var
var = var + num
print(var)
if __name__ == '__main__':
sums()
输出= 15
Let us make it easy for Beginner:-
- The
global
keyword will allow the global variable message to be assigned within the main function without producing a new local variable
message = "This is a global!"
def main():
global message
message = "This is a local"
print(message)
main()
# outputs "This is a local" - From the Function call
print(message)
# outputs "This is a local" - From the Outer scope
This concept is called Shadowing
- Sum a list of numbers in Python
nums = [1, 2, 3, 4, 5]
var = 0
def sums():
for num in nums:
global var
var = var + num
print(var)
if __name__ == '__main__':
sums()
Outputs = 15
回答 12
使用pairwise
itertools配方:
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) )
Using the pairwise
itertools recipe:
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) )
回答 13
简短:
def ave(x,y):
return (x + y) / 2.0
map(ave, a[:-1], a[1:])
外观如下:
>>> 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]
由于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]
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 map
over two lists, you do have to truncate the list, a[:-1]
. It works more as you’d expect if you use 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]
回答 14
如此众多的解决方案,但我最喜欢的仍然缺失:
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
numpy数组与列表没有太大区别(在这种情况下),除了可以将数组视为数字:
>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5 2.5 3.5 4.5]
做完了!
说明
花式索引的含义是:[1:]
包括从1到末尾的所有元素(因此省略元素0),并且[:-1]
是除最后一个元素之外的所有元素:
>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])
因此,将这两个元素相加即可得到一个由元素(1 + 2),(2 + 3)等组成的数组。并不是说我要除以2.0
,不是2
因为否则Python会认为您仅使用整数并产生四舍五入的整数结果。
使用numpy的优势
NumPy的可远快于各地的号码清单循环。根据列表的大小,速度快几个数量级。而且,它的代码少得多,至少对我来说,它更易于阅读。我正在尝试养成对所有数字组都使用numpy的习惯,这对我原本必须制作的所有循环和内部循环都是一个巨大的改进。
So many solutions, but my favourite is still missing:
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5])
a numpy array is not too different from a list (in this use case), except that you can treat arrays like numbers:
>>> ( arr[:-1] + arr[1:] ) / 2.0
[ 1.5 2.5 3.5 4.5]
Done!
explanation
The fancy indices mean this: [1:]
includes all elements from 1 to the end (thus omitting element 0), and [:-1]
are all elements except the last one:
>>> arr[:-1]
array([1, 2, 3, 4])
>>> arr[1:]
array([2, 3, 4, 5])
So adding those two gives you an array consisting of elemens (1+2), (2+3) and so on.
Not that I’m dividing by 2.0
, not 2
because otherwise Python believes that you’re only using integers and produces rounded integer results.
advantage of using numpy
Numpy can be much faster than loops around lists of numbers. Depending on how big your list is, several orders of magnitude faster. Also, it’s a lot less code, and at least to me, it’s easier to read.
I’m trying to make a habit out of using numpy for all groups of numbers, and it is a huge improvement to all the loops and lops-within-loops I would otherwise have had to make.
回答 15
我只是将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
I’d just use a lambda with 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
回答 16
我使用while
循环来获取结果:
i = 0
while i < len(a)-1:
result = (a[i]+a[i+1])/2
print result
i +=1
I use a while
loop to get the result:
i = 0
while i < len(a)-1:
result = (a[i]+a[i+1])/2
print result
i +=1
回答 17
遍历列表中的元素并像这样更新总数:
def sum(a):
total = 0
index = 0
while index < len(a):
total = total + a[index]
index = index + 1
return total
Loop through elements in the list and update the total like this:
def sum(a):
total = 0
index = 0
while index < len(a):
total = total + a[index]
index = index + 1
return total
回答 18
多亏了Karl Knechtel,我才能够理解您的问题。我的解释:
- 您想要一个包含元素i和i + 1平均值的新列表。
- 您要对列表中的每个元素求和。
使用匿名函数(又名Lambda函数)的第一个问题:
s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else [] #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else [] #assuming you want floor result
第二个问题也使用匿名函数(又名Lambda函数):
p = lambda l: l[0] + p(l[1:]) if l!=[] else 0
这两个问题合并在一行代码中:
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want floor result
使用最适合您需求的那个
Thanks to Karl Knechtel i was able to understand your question. My interpretation:
- You want a new list with the average of the element i and i+1.
- You want to sum each element in the list.
First question using anonymous function (aka. Lambda function):
s = lambda l: [(l[0]+l[1])/2.] + s(l[1:]) if len(l)>1 else [] #assuming you want result as float
s = lambda l: [(l[0]+l[1])//2] + s(l[1:]) if len(l)>1 else [] #assuming you want floor result
Second question also using anonymous function (aka. Lambda function):
p = lambda l: l[0] + p(l[1:]) if l!=[] else 0
Both questions combined in a single line of code :
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want result as float
s = lambda l: (l[0]+l[1])/2. + s(l[1:]) if len(l)>1 else 0 #assuming you want floor result
use the one that fits best your needs
回答 19
您也可以使用递归进行相同的操作:
Python片段:
def sumOfArray(arr, startIndex):
size = len(arr)
if size == startIndex: # To Check empty list
return 0
elif startIndex == (size - 1): # To Check Last Value
return arr[startIndex]
else:
return arr[startIndex] + sumOfArray(arr, startIndex + 1)
print(sumOfArray([1,2,3,4,5], 0))
You can also do the same using recursion:
Python Snippet:
def sumOfArray(arr, startIndex):
size = len(arr)
if size == startIndex: # To Check empty list
return 0
elif startIndex == (size - 1): # To Check Last Value
return arr[startIndex]
else:
return arr[startIndex] + sumOfArray(arr, startIndex + 1)
print(sumOfArray([1,2,3,4,5], 0))
回答 20
尝试使用列表理解。就像是:
new_list = [(old_list[i] + old_list[i+1])/2 for i in range(len(old_list-1))]
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))]
回答 21
本着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))
例子:
>>>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]
In the spirit of itertools. Inspiration from the pairwise recipe.
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]
回答 22
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)
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)
回答 23
一种简单的方法是使用iter_tools排列
# If you are given a list
numList = [1,2,3,4,5,6,7]
# and you are asked to find the number of three sums that add to a particular number
target = 10
# How you could come up with the answer?
from itertools import permutations
good_permutations = []
for p in permutations(numList, 3):
if sum(p) == target:
good_permutations.append(p)
print(good_permutations)
结果是:
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3,
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4,
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2),
(7, 2, 1)]
请注意,顺序很重要-意思是1、2、7也显示为2、1、7和7、1、2。您可以通过使用集合来减少此数目。
A simple way is to use the iter_tools permutation
# If you are given a list
numList = [1,2,3,4,5,6,7]
# and you are asked to find the number of three sums that add to a particular number
target = 10
# How you could come up with the answer?
from itertools import permutations
good_permutations = []
for p in permutations(numList, 3):
if sum(p) == target:
good_permutations.append(p)
print(good_permutations)
The result is:
[(1, 2, 7), (1, 3, 6), (1, 4, 5), (1, 5, 4), (1, 6, 3), (1, 7, 2), (2, 1, 7), (2, 3,
5), (2, 5, 3), (2, 7, 1), (3, 1, 6), (3, 2, 5), (3, 5, 2), (3, 6, 1), (4, 1, 5), (4,
5, 1), (5, 1, 4), (5, 2, 3), (5, 3, 2), (5, 4, 1), (6, 1, 3), (6, 3, 1), (7, 1, 2),
(7, 2, 1)]
Note that order matters – meaning 1, 2, 7 is also shown as 2, 1, 7 and 7, 1, 2. You can reduce this by using a set.
回答 24
在Python 3.8中,可以使用新的赋值运算符
>>> my_list = [1, 2, 3, 4, 5]
>>> itr = iter(my_list)
>>> a = next(itr)
>>> [(a + (a:=x))/2 for x in itr]
[1.5, 2.5, 3.5, 4.5]
a
是对列表中前一个值的运行引用,因此将其初始化为列表的第一个元素,并且迭代在列表的其余部分进行,a
并在每次迭代中使用后进行更新。
显式迭代器用于避免使用创建列表的副本my_list[1:]
。
In Python 3.8, the new assignment operator can be used
>>> my_list = [1, 2, 3, 4, 5]
>>> itr = iter(my_list)
>>> a = next(itr)
>>> [(a + (a:=x))/2 for x in itr]
[1.5, 2.5, 3.5, 4.5]
a
is a running reference to the previous value in the list, hence it is initialized to the first element of the list and the iteration occurs over the rest of the list, updating a
after it is used in each iteration.
An explicit iterator is used to avoid needing to create a copy of the list using my_list[1:]
.
回答 25
试试以下-
mylist = [1, 2, 3, 4]
def add(mylist):
total = 0
for i in mylist:
total += i
return total
result = add(mylist)
print("sum = ", result)
Try the following –
mylist = [1, 2, 3, 4]
def add(mylist):
total = 0
for i in mylist:
total += i
return total
result = add(mylist)
print("sum = ", result)