Python列表中奇数元素求和程序


在Python中,你可以通过以下几种方法找到现有列表中所有奇数元素的和:

  • 使用列表推导式

  • 使用循环

  • 使用filter()函数

使用列表推导式

列表推导式方法允许我们通过对列表中每个元素应用表达式或条件来创建一个新列表。

示例

遍历列表(nums)中的每个第I个元素,使用条件(if i % 2 == 1)过滤这些元素以仅返回奇数值,并使用sum()函数将过滤列表中的所有元素相加。

Open Compiler
def solve(nums): return sum([i for i in nums if i % 2 == 1]) nums = [13,27,12,10,18,42] print('The sum of odd elements is :',solve(nums))

输出

The sum of odd elements is :  40

使用循环

一种常见的遍历列表的方法是检查每个元素是否为奇数。

示例

在下面的示例代码中,将总和初始化为total = 0,使用for循环迭代每个元素,并使用(if i % 2 == 1)检查奇数元素,并将这些元素添加到total中。

Open Compiler
def solve(nums): total = 0 for i in nums: if i % 2 == 1: total += i return total nums = [5,7,6,4,6,9,3,6,2] print('The sum of odd elements is :',solve(nums))

输出

The sum of odd elements is:  24

Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.

使用filter()函数

filter()用于创建一个迭代器,该迭代器根据给定条件过滤现有列表中的元素。

示例

在下面的示例代码中,使用filter(lambda x: x % 2 == 1, nums)函数过滤列表中的奇数,并将过滤后的列表传递给sum()函数。

Open Compiler
def solve(nums): return sum(filter(lambda x: x % 2 == 1, nums)) nums = [5,7,6,4,6,3,6,2] print('The sum of odd elements is :',solve(nums))

输出

The sum of odd elements is :  15

更新于:2024年10月4日

6K+ 浏览量

开启你的职业生涯

完成课程获得认证

开始学习
广告