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

本文介绍了两种在Python中计算数组所有元素总和的方法。第一种方法是遍历数组中的每个元素并将其累加到一个变量中;第二种方法是使用Python内置的sum()函数直接计算总和。通过实例演示了两种方法的具体实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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数组查找元素

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值