python数组查找元素_Python程序查找数组所有元素的总和

python数组查找元素

Given an integer array and we have to find the sum of all elements in Python.

给定一个整数数组,我们必须找到Python中所有元素的总和

查找数组元素的总和 (Finding the sum of array elements)

There are two ways to find the sum of all array elements, 1) traverse/access each element and add the elements in a variable sum, and finally, print the sum. And, 2) find the sum of array elements using sum() function.

有两种查找所有数组元素之和的方法: 1)遍历/访问每个元素并将元素添加到变量sum中 ,最后打印出sum 。 并且2)使用sum()函数找到数组元素的总和

Example:

例:

    Input: 
    arr = [10, 20, 30, 40, 50]
    Output:
    sum = 150

用于数组元素求和的Python程序 (Python program for sum of the array elements)

# Python program for sum of the array elements

# functions to find sum of elements

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

# main function
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    print ('sum_1: {}'.format(sum_1(arr)))
    print ('sum_2: {}'.format(sum_2(arr)))

Output

输出量

sum_1: 150
sum_2: 150


翻译自: https://www.includehelp.com/python/find-the-sum-of-all-elements-of-an-array.aspx

python数组查找元素

    原文作者:cumtv80668
    原文地址: https://blog.csdn.net/cumtv80668/article/details/107800184
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞