列表中连续对的和,包括最后一个元素与第一个元素的和 [英] Sum of consecutive pairs in a list including a sum of the last element with the first
本文介绍了列表中连续对的和,包括最后一个元素与第一个元素的和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像[1,3,5,6,8,7]
这样的元素列表.
我想要一个列表中两个连续元素的和的列表,以使最后一个元素也与列表的第一个元素相加.
我的意思是在上述情况下,我需要此列表:
[4,8,11,14,15,8]
I have a list of elements like [1,3,5,6,8,7]
.
I want a list of sums of two consecutive elements of the list in a way that the last element is also added with the first element of the list.
I mean in the above case, I want this list:
[4,8,11,14,15,8]
但是在for循环中添加最后一个元素和第一个元素时,索引超出范围. 考虑以下代码:
But when it comes to the addition of the last and the first element during for loop, index out of range occurs. Consider the following code:
List1 = [1,3,5,6,8,7]
List2 = [List1[i] + List1[i+1] for i in range (len(List1))]
print(List2)
推荐答案
List2 = [List1[i] + List1[(i+1)%len(List1)] for i in range (len(List1))]
这篇关于列表中连续对的和,包括最后一个元素与第一个元素的和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文