# Python在list中的替代元素求和

2021年3月17日18:09:55 发表评论 658 次浏览

``````# 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]``````

``````# 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]``````