[英]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]
但是在for循环中添加最后一个元素和第一个元素时,会出现索引超出范围。 考虑以下代码:
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))]
[List1[i] + List1[(i+1) % len(List1)] for i in range(len(List1))]
或者
[sum(tup) for tup in zip(List1, List1[1:] + [List1[0]])]
或者
[x + y for x, y in zip(List1, List1[1:] + [List1[0]])]
由于i+1
,索引超出范围
List1 = [1,3,5,6,8,7]
List2 = [List1[i-1] + List1[i] for i in range (len(List1))]
print (List2)
这种方式有点工作
结果:
[8, 4, 8, 11, 14, 15]
这会旋转列表
In [9]: List1[1:] + List1[:1]
Out[9]: [3, 5, 6, 8, 7, 1]
所以以下工作完美
In [8]: [x + y for x, y in zip(List1, List1[1:] + List1[:1])]
Out[8]: [4, 8, 11, 14, 15, 8]
您实际上在做的是在列表中添加连续的项目,但是当您到达最后一个索引时,您的代码仍然会在最后一个索引中添加一个,这会导致索引超出范围错误。 您应该考虑使用:
List1 = [1,3,5,6,8,7]
List2 = [List1[i] + List1[i+1] for i in range (len(List1) - 1)]
List2.append(List1[0] + List1[-1])
print (List2)
当您将其运行到 len(List1) - 1 时,i 值将为 len(List1) - 1,然后 i + 1 将超出范围(即 len(List1)),因此您可以尝试此解决方案:
List2 = [List1[i-1] + List1[i] for i in range (len(List1))]
或者你可以这样做:
List2 = [List1[i] + List1[i+1] for i in range (len(List1)-1)]
或者您也可以使用任何其他逻辑。 干杯!
当i == 5
时,它将进入“if”语句并且i
设置为-1
。 请注意, List[-1]
与List[len(List) - 1]
相同,这意味着List[i+1]
将成为List[0]
,即列表的第一个元素。
for i in range(len(List1)):
if i == len(List1) - 1:
i = -1
List2.append(List1[i] + List1[i+1])
这是另一个丑陋的解决方案:
List1 = [1,3,5,6,8,7]
List2 = [List1[i] + (List1+[List1[0]])[i+1] for i in range (len(List1))]
print (List2)
还有一些尚未回答的pythonic答案:
使用map
可以更具可读性:
List2 = list(map(sum, zip(List1, List1[1:] + List1[:1])))
您还可以使用itertools
来偏移列表:
import itertools
List2 = list(map(sum, zip(List1, itertools.islice(itertools.cycle(List1), 1, None))))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.