我有以下四个元素的数组:
arr = [{"location": 10, "value": 50}, {"location": 21, "value": 70}, {"location": 33, "value": 20}, {"location": 48, "value": 0}]
我想创建一个由三个元素组成的新数组,组合相邻的项:[ {index 0, 1}, {index 1, 2}, {index 2, 3} ]
在每对上运行的函数很简单:
def combine(current, next):
return (next["location"] - current["location"]) * current["value"]
显然,这可以使用循环来完成,但是有没有更Pythonic的方法来实现这一点? 我想生成以下输出:
[550, 840, 500] // (21 - 10) * 50, (33 - 21) * 70, (48 - 33) * 20
您可以使用
zip(arr, arr[1:])
:
def get_combine_neighbors(A):
_comb = lambda x, y: (y["location"] - x["location"]) * x["value"]
return [_comb(x, y) for x, y in zip(A, A[1:])]
A = [{"location": 10, "value": 50}, {"location": 21, "value": 70},
{"location": 33, "value": 20}, {"location": 48, "value": 0}]
print(get_combine_neighbors(A))
[550, 840, 300]