1

I know a map function gets a function as its first argument and the next arguments are iterators on which the passed function needs to be applied. My question here is say if I have a 2d list like so

l=[[1,2,3],[4,5,6],[7,8,9]]

how can I sort the individual lists in reverse order so my output is

l=[[3,2,1],[6,5,4],[9,8,7]]

I know a potential solution is using a lambda function such as

list(map(lambda x:x[::-1],l))

I want something like this

list(map(sorted, l,'reversed=True'))

where 'reversed=True' is an argument that sorted takes

eg:

>>> newList=[1,2,3]
>>> sorted(newList,reversed='True')
>>> [3,2,1]

I have seen how to pass arguments to a the pow function using the itertools.repeat module

map(pow,list,itertools.repeat(x))

x=power to which the list must be raised

I want to know if there is any way the arguments can be passed in a map function. In my case the 'reverse=True' for the sorted function.

1
  • Your solution using a lambda is, I believe, the one you should favor. Commented Apr 15, 2019 at 13:18

4 Answers 4

4

You can use functools.partial for this:

import functools

new_list = list(map(functools.partial(sorted, reverse=True), l))
Sign up to request clarification or add additional context in comments.

3 Comments

I was gonna post this because it is the way to go. But wrote the other option instead because you were first ;)
functools.partial is the python way for currying functions.
@TheNamesAlc Yes that's exactly how it works, you can read more from the documentation: docs.python.org/3/library/functools.html#functools.partial
3

You can use a lambda to wrap the funtion:

map(lambda x: sorted(x, reversed=True), l)

or:

map(lambda i, j: pow(i, j), list,itertools.repeat(x))

1 Comment

Which is what lambda allows you to do.
2

There are many ways to do it.

You could use functools.partial. It creates a partial, for the lack of a better word, of the function you pass to it. It sort of creates a new function with some parameters already passed into it.

For your example, it would be:

from functools import partial
rev_sort = partial(sorted, reverse=True)
map(rev_sort, l)

The other way is using a simple lambda:

map(lambda arr: sorted(arr, reverse=True), l)

The other other way (my personal choice), is using generators:

(sorted(arr, reverse=True) for arr in l)

1 Comment

You are correct. 2 and 3 are technically the same. They are both lazily evaluated. The only difference is syntax, as far as I know. I prefer the third one because, for me, it is easier to understand.
-1

For this specific case, you can also use a list comprehension -

l=[[1,2,3],[4,5,6],[7,8,9]]

l = [list(reversed(sublist)) for sublist in l] //[[3,2,1],[6,5,4],[9,8,7]]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.