Python在list中的替代元素求和

获取列表求和的问题是非常普遍的问题, 有一天我们可能会面临获取替代元素求和并获得包含替代元素求和的2个元素的列表的问题。让我们讨论执行此操作的某些方法。
方法#1:使用列表理解+列表切片+ sum()
与列表理解结合在一起的列表切片可用于执行此特定任务。我们可以有列表理解来运行逻辑, 列表切片可以切出替代字符, 由求和函数求和

# Python3 code to demonstrate # alternate elements summation # using list comprehension + list slicing# initializing list test_list = [ 2 , 1 , 5 , 6 , 8 , 10 ]# printing original list print ( "The original list : " + str (test_list))# using list comprehension + list slicing # alternate elements summation res = [ sum (test_list[i : : 2 ]) for i in range ( len (test_list) / / ( len (test_list) / / 2 ))]# print result print ( "The alternate elements summation list : " + str (res))

输出:
The original list : [2, 1, 5, 6, 8, 10] The alternate elements summation list : [15, 17]

方法2:使用循环
【Python在list中的替代元素求和】这是执行此特定任务的简单方法, 其中我们将不同元素索引中的替代元素相加, 然后返回输出列表。
# Python3 code to demonstrate # alternate elements summation # using loop# initializing list test_list = [ 2 , 1 , 5 , 6 , 8 , 10 ]# printing original list print ( "The original list : " + str (test_list))# using loop # alternate elements summation res = [ 0 , 0 ] for i in range ( 0 , len (test_list)): if (i % 2 ): res[ 1 ] + = test_list[i] else : res[ 0 ] + = test_list[i]# print result print ( "The alternate elements summation list : " + str (res))

输出:
The original list : [2, 1, 5, 6, 8, 10] The alternate elements summation list : [15, 17]

注意!巩固你的基础Python编程基础课程和学习基础知识。
首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。

    推荐阅读