[英]Python - reduce ,two dimensional array
I 'm trying to use reduce on two-dimensional array which consists of coordinates.I don't have a lot of experience with reduce .I have a function called func and I have to apply this function to each element of the array. 我试图用降低二维数组其中包括coordinates.I的没有很多的经验。我减少有一个函数调用FUNC,我有这个功能应用到阵列中的每个元素。 For example:
例如:
func=lambda x:x-1
array=[[5,9],[10,3]]
reduce (lambda x,y: ...,array)
OUTPUT should be -> [[4,8],[9,2]]
I just decrement each element by 1 . 我只是将每个元素递减1。 Thanks.
谢谢。
reduce
takes a function of two arguments and applies it cumulatively to the elements of a sequence - but all you want to do is subtract one from every element of every sublist, so I'm not sure why you would want to use reduce
here. reduce
使用两个参数的函数并将其累积地应用于序列的元素 - 但是你想要做的就是从每个子列表的每个元素中减去一个,所以我不确定你为什么要在这里使用reduce
。
I suggest this list comprehension: 我建议这个列表理解:
>>> lst = [[5,9],[10,3]]
>>> [[x-1 for x in sub] for sub in lst]
[[4, 8], [9, 2]]
Or if you want to use your lambda function: 或者如果你想使用你的lambda函数:
>>> [map(lambda x: x-1, sub) for sub in lst]
[[4, 8], [9, 2]]
I find the first one to be more readable, though. 不过,我发现第一个更具可读性。
you don't need to use reduce to decrease each element's value. 您不需要使用reduce来减少每个元素的值。
Try using map 尝试使用地图
arr = map( lambda x:[x[0]-1,x[1]-1],arr)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.