Processing math: 100%

Python - 找出列表第一个偶数元素和最后一个偶数元素之间的距离


如果需要找出列表第一个偶数元素和最后一个偶数元素之间的距离,则可以使用索引访问列表元素,并找出差值。

示例

以下是对其进行演示

Open Compiler
my_list = [2, 3, 6, 4, 6, 2, 9, 1, 14, 11] print("The list is :") print(my_list) my_indices_list = [idx for idx in range( len(my_list)) if my_list[idx] % 2 == 0] my_result = my_indices_list[-1] - my_indices_list[0] print("The result is :") print(my_result)

输出

The list is :
[2, 3, 6, 4, 6, 2, 9, 1, 14, 11]
The result is :
8

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

说明

  • 定义一个列表并将其显示在控制台中。

  • 迭代列表,并检查元素是否可被 2 整除。

  • 如果是,它们将被分配给一个变量。

  • 通过索引它们来获得最后一个元素和第一个元素之间的差值。

  • 此差值分配给一个变量。

  • 此变量显示在控制台中。

更新于: 2021 年 9 月 20 日

349 次浏览

开启您的 职业生涯

完成课程获取认证

入门
广告