如何在列表中添加相邻的数字?我无法获取最后一个变量



x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]

使用for循环在x中添加相邻元素
将每个结果存储在一个向量sa
同时显示矢量x和矢量sa。例如,sa的前3个数字将是:

sa = [11, 9, 12, …]  = [(3+8), (3+8+(-2)), (8+(-2)+6), …] 

我有这样的东西。。。

x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]
sa = []
for i in range (0, len(x)-1):
if i<1:
sa.append(x[0] + x[1])
elif i >= 1 & i< len(x):
sa.append(x[i-1] + x[i] + x[i+1])
if i == 0:
sa.append(x[i] + x[i+1])
print("Here is sa", sa) 

但我无法获得-5+8的最后一个变量,请帮忙我最终得到的是这是sa[11, 11, 9, 12, 13, 11, 12, 4, 3, 4]但我还需要最后一个值,它应该是(-5+8(=3,所以最终的总答案应该包括三个,比如

[11, 11, 9, 12, 13, 11, 12, 4, 3, 4, 3]

甚至

[11, 9, 12, 13, 11, 12, 4, 3, 4, 3]

您可以将其写成列表理解,注意sa中的第i个元素是从x[i-1]x[i+1]x值中的sum。现在这些索引可能会超出x的边界,所以我们需要使用maxmin来将它们保持在范围内:

x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]
sa = [sum(x[max(i-1, 0):min(i+2, len(x))]) for i in range(len(x))]
print(sa)

输出:

[11, 9, 12, 13, 11, 12, 4, 3, 4, 3]

如果您正在寻找非全面的方法,这里就是。

for i in range(len(x)):
if i == 0:
sa.append(x[i] + x[i+1])
elif 1 <= i < len(x)-1:
sa.append(x[i-1] + x[i] + x[i+1])
else:
sa.append(x[i] + x[i-1])
print("Here is sa", sa)

输出:

Here is sa [11, 9, 12, 13, 11, 12, 4, 3, 4, 3]

您的代码有一些错误:

x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]
sa = []
# the last element of the loop will be x[len(x)-2], it is -5 in this case
# -5 is the last element this loop process, it adds up 1, -5 and 8
# this loop will not take 8 as the central number, so the results miss the last value
for i in range (0, len(x)-1):
if i<1:
sa.append(x[0] + x[1])
# in python, it is `and` not &, & is bitwise and.
elif i >= 1 & i< len(x):
sa.append(x[i-1] + x[i] + x[i+1])
if i == 0: # this is meaningless, i == 0 is covered in the first if branch
sa.append(x[i] + x[i+1])
print("Here is sa", sa)

修复您的代码:

x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]
sa = []
# fix one: loop to the last element
for i in range (0, len(x)):
if i<1:
sa.append(x[0] + x[1])
# fix two: do not include the last element in this elif branch
elif i >= 1 and i < len(x) - 1:
sa.append(x[i-1] + x[i] + x[i+1])
# fix three: process the last element.
else:
sa.append(x[i - 1] + x[i])
print("Here is sa", sa)

输出:

Here is sa [11, 9, 12, 13, 11, 12, 4, 3, 4, 3]
>>> x = [3, 8, -2, 6, 9, -4, 7, 1, -5, 8]

用前两个元素的总和创建一个列表,

>>> q = [sum(x[:2])]

在列表上一次迭代三次,并将总和相加。

>>> for thing in zip(x,x[1:],x[2:]):
...     q.append(sum(thing))

将最后两项的总和相加。

>>> q.append(sum(x[-2:]))
>>> q
[11, 9, 12, 13, 11, 12, 4, 3, 4, 3]

最新更新