简体   繁体   中英

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. 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 . 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.

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:

>>> [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.
Try using map

arr = map( lambda x:[x[0]-1,x[1]-1],arr)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM