Adn*_*ram 7 python for-loop list
我有一个像[1,3,5,6,8,7]. 我想要一个列表的两个连续元素的总和列表,其中最后一个元素也与列表的第一个元素相加。我的意思是在上述情况下,我想要这个列表:
[4,8,11,14,15,8]
但是当在for循环中添加最后一个和第一个元素时,就会出现index out of range。考虑以下代码:
List1 = [1,3,5,6,8,7]
List2 = [List1[i] + List1[i+1] for i in range (len(List1))]
print(List2)
Run Code Online (Sandbox Code Playgroud)
List2 = [List1[i] + List1[(i+1)%len(List1)] for i in range (len(List1))]
Run Code Online (Sandbox Code Playgroud)