Python 编写一个对数字列表求和的自定义求和函数

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

Writing a custom sum function that sums a list of numbers

pythonloopsfor-loop

提问by Blnpwr

I am new to Python and need some help writing a function that takes a list as an argument.

我是 Python 新手,需要一些帮助来编写一个将列表作为参数的函数。

I want a user to be able to enter a list of numbers (e.g., [1,2,3,4,5]), and then have my program sum the elements of the list. However, I want to sum the elements using a for loop, not just by using the built in sumfunction.

我希望用户能够输入数字列表(例如,[1,2,3,4,5]),然后让我的程序对列表中的元素求和。但是,我想使用 for 循环对元素求和,而不仅仅是使用内置sum函数。

My problem is that I don't know how to tell the interpreter that the user is entering a list. When I use this code:

我的问题是我不知道如何告诉解释器用户正在输入一个列表。当我使用此代码时:

  def sum(list):

It doesn't work because the interpreter wants just ONE element that is taken from sum, but I want to enter a list, not just one element. I tried using list.append(..), but couldn't get that to work the way I want.

它不起作用,因为解释器只需要从 sum 中提取的一个元素,但我想输入一个列表,而不仅仅是一个元素。我尝试使用 list.append(..),但无法按照我想要的方式工作。

Thanks in anticipation!

感谢期待!

EDIT: I am looking for something like this (thanks, "irrenhaus"):

编辑:我正在寻找这样的东西(谢谢,“irrenhaus”):

def listsum(list):
    ret=0
    for i in list:
        ret += i
    return ret

# The test case:
print listsum([2,3,4])  # Should output 9.

采纳答案by Adam Smith

I'm not sure how you're building your "user entered list." Are you using a loop? Is it a pure input? Are you reading from JSON or pickle? That's the big unknown.

我不确定您是如何构建“用户输入列表”的。你在使用循环吗?是纯输入吗?您是从 JSON 还是 pickle 中读取数据?这就是最大的未知数。

Let's say you're trying to get them to enter comma-separated values, just for the sake of having an answer.

假设您试图让他们输入逗号分隔的值,只是为了得到答案。

# ASSUMING PYTHON3

user_input = input("Enter a list of numbers, comma-separated\n>> ")
user_input_as_list = user_input.split(",")
user_input_as_numbers_in_list = map(float, user_input_as_list) # maybe int?
# This will fail if the user entered any input that ISN'T a number

def sum(lst):
    accumulator = 0
    for element in lst:
        accumulator += element
    return accumulator

The top three lines are kind of ugly. You can combine them:

前三行有点丑。你可以组合它们:

user_input = map(float, input("Enter a list of numbers, comma-separated\n>> ").split(','))

But that's kind of ugly too. How about:

但这也有点丑。怎么样:

raw_in = input("Enter a list of numbers, comma-separated\n>> ").split(',')
try:
    processed_in = map(float, raw_in)
    # if you specifically need this as a list, you'll have to do `list(map(...))`
    # but map objects are iterable so...
except ValueError:
    # not all values were numbers, so handle it

回答by Nishant Nawarkhede

Here the function addelementsaccept list and return sum of all elements in that list only if the parameter passed to function addelementsis listand all the elements in that list are integers. Otherwise function will return message "Not a list or list does not have all the integer elements"

这里函数addelements接受列表并返回该列表中所有元素的总和,仅当传递给函数的参数addelementslist并且该列表中的所有元素都是integers。否则函数将返回消息“不是列表或列表没有所有整数元素”

def addelements(l):
    if all(isinstance(item,int) for item in l) and isinstance(l,list):
        add=0
        for j in l:
            add+=j
        return add
    return 'Not a list or list does not have all the integer elements'

if __name__=="__main__":
    l=[i for i in range(1,10)]
#     l.append("A") This line will print msg "Not a list or list does not have all the integer elements"
    print addelements(l)

Output:

输出:

45

回答by irrenhaus3

The for loop in Python is exceptionally easy to use. For your application, something like this works:

Python 中的 for 循环非常容易使用。对于您的应用程序,如下所示:

def listsum(list):
    ret=0
    for i in list:
        ret+=i
    return ret

# the test case:
print listsum([2,3,4])
# will then output 9

Edit: Aye, I am slow. The other answer is probably way more helpful. ;)

编辑:是的,我很慢。另一个答案可能更有帮助。;)

回答by llrs

This will work for python 3.x, It is similar to the Adam Smith solution

这适用于 python 3.x,类似于 Adam Smith 解决方案

list_user = str(input("Please add the list you want to sum of format [1,2,3,4,5]:\t"))
total = 0
list_user = list_user.split() #Get each element of the input
for value in list_user:
    try:
        value = int(value) #Check if it is number
    except:
        continue
    total += value

print(total)

回答by mgg07

import math



#get your imput and evalute for non numbers

test = (1,2,3,4)

print sum([test[i-1] for i in range(len(test))])
#prints 1 + 2 +3 + 4 -> 10
#another sum with custom function
print math.fsum([math.pow(test[i-1],i) for i in range(len(test))])
#this it will give result 33 but why? 
print [(test[i-1],i) for i in range(len(test))]
#output -> [(4,0), (1, 1) , (2, 2), (3,3)] 
# 4 ^ 0 + 1 ^ 1 + 2 ^ 2 + 3 ^ 3 -> 33

回答by Przemek

You can even write a function that can sum elements in nested list within a list. For example it can sum [1, 2, [1, 2, [1, 2]]]

您甚至可以编写一个函数,该函数可以对列表中嵌套列表中的元素进行求和。例如它可以求和[1, 2, [1, 2, [1, 2]]]

    def my_sum(args):
    sum = 0
    for arg in args:
        if isinstance(arg, (list, tuple)):
            sum += my_sum(arg)
        elif isinstance(arg, int):
            sum += arg
        else:
            raise TypeError("unsupported object of type: {}".format(type(arg)))
    return sum

for my_sum([1, 2, [1, 2, [1, 2]]])the output will be 9.

因为 my_sum([1, 2, [1, 2, [1, 2]]])输出将是9.

If you used standard buildin function sumfor this task it would raise an TypeError.

如果您sum为此任务使用标准内置函数,它将引发TypeError.

回答by Rafael Díaz

This is a somewhat slow version but it works wonders

这是一个有点慢的版本,但效果很好

# option 1
    def sumP(x):
        total = 0
        for i in range(0,len(x)):
            total = total + x[i]
        return(total)    

# option 2
def listsum(numList):
   if len(numList) == 1:
        return numList[0]
   else:
        return numList[0] + listsum(numList[1:])

sumP([2,3,4]),listsum([2,3,4])

回答by Olalere Micheal Olasunkanmi

This should work nicely

这应该很好用

user_input =  input("Enter a list of numbers separated by a comma")
user_list = user_input.split(",")

print ("The list of numbers entered by user:" user_list)


ds = 0
for i in user_list:
    ds += int(i)
print("sum = ", ds)

}

}