[英]Python sum items in sequence
从坐标的起始列表(xCoord 变量)我想对这些值(Offset_X 变量)应用偏移量。 Offset_X 是一个包含长度等于 xCoord 的子列表的列表。
重要的是要强调 xCoord 变量 (xCoord[0]) 的第一项将求和 Offset_X 列表中第一个子列表的第一项,然后,该结果将求和第一个子列表中的第二项。
请找到包含输入的屏幕截图和我落后的最终结果(new_xCoord 变量):
xCoord = [2,5]
Offset_X = [[3,4,6],[1,5,3,4]]
new_xCoord = [[5,9,15],[6,11,14,18]] # <- result
谢谢,
可能有更有效的方法来做到这一点,但这有效......
xCoord = [2,5]
Offset_X = [[3,4,6],[1,5,3,4]]
def calc(xCoord, Offset_X):
new_xCoord = [] # create new coords list
for cor, offs in zip(xCoord, Offset_X): # iterate the coords and offset
inter = cor
arr = [] # create empty list
for off in offs: # iterate the current coordinates offset list
inter += off # increase value by the offset
arr.append(inter) # append it to the list
new_xCoords.append(arr) # append the list to new coords list
return new_xCoords # return the new coords list
print(calc(xCoord, Offset_X))
OUTPUT
[[5, 9, 15], [6, 11, 14, 18]]
更新
以下示例可能表现更好,因为使用itertools
模块通常会提供更有效的解决方案。
import itertools
xCoord = [2,5]
Offset_X = [[3,4,6],[1,5,3,4]]
def calc(xCoord, Offset_X):
new_xCoord = []
for cor, offs in zip(xCoord, Offset_X):
offs[0] += cor
new_xCoord.append(list(itertools.accumulate(offs)))
return new_xCoords
print(calc(xCoord, Offset_X))
引入帮助器 function 使其可以作为列表理解来解决,因此您不必 append 来列表。 Accumulate 保留 arrays 中每个元素的运行总计,并一次生成一个总计。
def accumulate(x, offsets):
new_x = x
for offset in offsets:
new_x += offset
yield(new_x)
new_xCoord = [list(accumulate(x, offsets))for x, offsets in zip(xCoord, Offset_X)]
您可以为此使用内置模块itertools
,它有 function 累积,这可能很方便。
from itertools import accumulate
print([list(accumulate(o, initial=x))[1:] for x, o in zip(xCoord, Offset_X)])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.