Python - 找出列表第一个偶数元素和最后一个偶数元素之间的距离
如果需要找出列表第一个偶数元素和最后一个偶数元素之间的距离,则可以使用索引访问列表元素,并找出差值。
示例
以下是对其进行演示
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
说明
定义一个列表并将其显示在控制台中。
迭代列表,并检查元素是否可被 2 整除。
如果是,它们将被分配给一个变量。
通过索引它们来获得最后一个元素和第一个元素之间的差值。
此差值分配给一个变量。
此变量显示在控制台中。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP