3 回答
TA贡献1842条经验 获得超12个赞
如果我正确理解您的要求,您可以使用pandas. 例如:
import pandas as pd
# Create a pandas Series of values
s = pd.Series([-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2])
# Add the current value in the series to the 'shifted' (previous) value.
output = s.add(s.shift(1), fill_value=0).tolist()
# Display the output.
print(output)
输出:
[-2.0, -4.0, -3.0, 0.0, 0.0, 0.0, 4.0, 8.0, 11.0, 4.0, -3.0, -1.0, -2.0, -3.0, -3.0, 0.0]
TA贡献1719条经验 获得超6个赞
list1 = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2]
new_list=[list1[0]]
for i in range(len(list1)-1):
value=list1[i]+list1[i+1]
new_list.append(value)
print(new_list)
Output:[-2,-4,-3, 0, 0, 0, 4, 8, 11, 4, -3, -1, -2, -3, -3, 0]
TA贡献1802条经验 获得超4个赞
您必须迭代列表并添加数字,如下所示:
list = [-2, -2, -1, 1, -1, 1, 3, 5, 6, -2, -1, 0, -2, -1, -2, 2]
new_list = list[0] # We just take the first element of the list, because we don't add anything
for number, element in enumerate(list[1:]):
new_list.append(element + list[number - 1])
或者更pythonic的方式:
new_list = [list[0]].extend([element + list[number - 1] for number, element in enumerate (list[1:])
添加回答
举报