Python|交替前 - 后总和
在使用Python时,我们通常会遇到许多需要在日常和开发中解决的问题。特别是在开发中, Python的小任务希望在一行中执行。我们讨论了一些计算列表的方法,该列表由列表中交替前后总和的元素组成。
方法#1:使用循环
这是可以解决此问题的蛮力方法。在此,我们取两个指针并将它们的和存储在数组中,同时增加和减少它们的位置。
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using loop
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using loop
res = []
j = len(test_list) - 1
for i in range(0, len(test_list) // 2):
res.append(test_list[i] + test_list[j])
j = j - 1
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using list comprehension
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using list comprehension
res = [test_list[i] + test_list[len(test_list) - (i + 1)] for i in range(len(test_list) // 2)]
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
输出
The original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]
方法#2:使用列表推导
可以使用朴素的方法来执行,但列表推导提供了一种单一的方法来执行此任务。
Python3
# Python3 code to demonstrate
# Alternate front - rear Sum
# using list comprehension
# initializing list
test_list = [1, 4, 5, 3, 6, 7]
# printing original list
print ("The original list is : " + str(test_list))
# Alternate front - rear Sum
# using list comprehension
res = [test_list[i] + test_list[len(test_list) - (i + 1)] for i in range(len(test_list) // 2)]
# printing result
print ("The alternate front - rear Sum list is : " + str(res))
输出
The original list is : [1, 4, 5, 3, 6, 7]
The alternate front - rear Sum list is : [8, 10, 8]