Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/351.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
用Python对数字列表求和_Python_List_Sum - Fatal编程技术网

用Python对数字列表求和

用Python对数字列表求和,python,list,sum,Python,List,Sum,我有一个数字列表,比如[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 要一个号码 这对我不起作用。数字总和列表: sum(list_of_nums) 使用以下公式计算n和n-1的一半(如果模式正确): 对相邻

我有一个数字列表,比如
[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
要一个号码

这对我不起作用。

数字总和列表:

sum(list_of_nums)
使用以下公式计算n和n-1的一半(如果模式正确):

对相邻元素求和,例如:(1+2)/2)+(2+3)/2)+。。。使用及

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

我们制作两个列表:一个是除第一个元素外的每个元素,另一个是除最后一个元素外的每个元素。然后,我们想要的平均值是从两个列表中得到的每一对的平均值。我们使用
zip
从两个列表中提取配对

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

因此:

问题2:

使用
sum
应该可以。以下工作:

a = range(10)
# [0,1,2,3,4,5,6,7,8,9]
b = sum(a)
print b
# Prints 45
此外,您不需要在过程中的每一步都将所有内容分配给变量<代码>打印总和(a)工作正常


你必须更具体地说明你写了什么以及它是如何工作的。

尝试使用列表理解。比如:

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

生成器是编写以下内容的简单方法:

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]

本着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]

两两使用

简明扼要:

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]
导入itertools >>>imap(ave,a,a[1:]) >>>名单 [0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.5, 7.5, 8.5]
我只需要将lambda与map()一起使用

>a=范围(10)
>>>总数(a)
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
TypeError:“int”对象不可调用
>>>德尔苏姆
>>>总数(a)
45

似乎
sum
已在代码中的某个地方定义,并覆盖了默认函数。所以我删除了它,问题就解决了。

所有的答案都显示了一种程序化和通用的方法。我建议针对您的案例采用一种数学方法。它可以更快,特别是对于长列表。它之所以有效,是因为您的列表是一个自然数列表,最多为
n

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)
假设我们有自然数
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
,其中
n
是列表中最后一个元素的值(此处:
nat_seq[-1]
),因此可以避免对元素进行迭代:

>>> print (nat_seq[-1]*(nat_seq[-1]+1))/2
55
>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5
要生成序列
(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 (nat_seq[-1]*(nat_seq[-1]+1))/2
55
>>> print (((new_seq[-1]*2+1)/2)**2-1)/2
49.5

使用简单的
列表理解
总和

>> sum(i for i in range(x))/2. #if x = 10 the result will be 22.5

解决此问题的最简单方法是:

l =[1,2,3,4,5]
sum=0
for element in l:
    sum+=element
print sum
尝试下列方法:

mylist = [1, 2, 3, 4]   

def add(mylist):
    total = 0
    for i in mylist:
        total += i
    return total

result = add(mylist)
print("sum = ", result)

问题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)

我使用
while
循环来获得结果:

i = 0
while i < len(a)-1:
   result = (a[i]+a[i+1])/2
   print result
   i +=1
i=0
而i
循环列表中的元素,并按如下方式更新总数:

def sum(a):
    total = 0
    index = 0
    while index < len(a):
        total = total + a[index]
        index = index + 1
    return total
定义和(a): 总数=0 索引=0 当指数您可以这样尝试:

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

一个简单的方法是使用iter_工具排列

# 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。你可以用一套来减少这个问题。

多亏了卡尔·克内赫特尔,我才能够理解你的问题。我的解释是:

  • 您需要一个元素i和i+1的平均值的新列表
  • 您希望对列表中的每个元素求和
  • 第一个使用匿名函数(又称Lambda函数)的问题:

    第二个问题也使用匿名函数(又称Lambda函数):

    两个问题组合在一行代码中:

    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
    

    使用最适合您需要的工具

    让我们为初学者提供方便:-

  • global
    关键字将允许在主函数中分配全局变量消息,而不产生新的局部变量
  • 这个概念被称为阴影

  • 用Python对数字列表求和

  • 输出=15

    此问题已得到回答


    sum(a)返回10个

    如此多的解决方案,但我最喜欢的仍然缺少:

    >>> 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:://code>包括从1到结尾的所有元素(因此省略了元素0),
    [:-1]
    是除最后一个之外的所有元素:

    >>> arr[:-1]
    array([1, 2, 3, 4])
    >>> arr[1:]
    array([2, 3, 4, 5])
    
    [(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)]
    
    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
    
    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
    
        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
    
    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()
    
    a = [1,2,3,4]
    sum(a) 
    
    >>> import numpy as np
    >>> arr = np.array([1,2,3,4,5])
    
    >>> ( arr[:-1] + arr[1:] ) / 2.0
    [ 1.5  2.5  3.5  4.5]
    
    >>> arr[:-1]
    array([1, 2, 3, 4])
    >>> arr[1:]
    array([2, 3, 4, 5])
    
    >>> 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]
    
    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))