I have a list of words
that I am trying to sort
within a list:
words = ["yo", "act", "flop",'tac']
words = list(map(sorted,words))
Desired outcome: ['oy','act','flop','act']
The above splits up each word inside words into individual characters- but does sort it:
- why does it do this? Because we are just sorting?
- how can I rejoin them so that they are words again rather than individual characters? I know it is using
"".join()
, but I can't seem to wrap this around the above!
Thanks!
CodePudding user response:
sorted
works on arbitrary iterable values, but always returns a list, not a value of the same iterable it just sorted.
>>> sorted("yo")
['o', 'y']
That means you have to take the sorted list and turn it back into a string yourself.
>>> [''.join(sorted(x)) for x in words]
['oy', 'act', 'flop', 'act']
You can still use map
, but it's a little messier than just using a list comprehension:
>>> list(map(lambda x: ''.join(sorted(x)), words))
['oy', 'act', 'flop', 'act']
Because Python doesn't support function composition natively, you can't write something concise (and possibly more efficient) like
list(map(''.join ∘ sorted, words))
(where ∘
is a hypothetical operator that behaves like
(f ∘ g) == lambda x: f(g(x))
)
Composition always involves creating an additional function that needs to be called in order to call the original two functions, rather than creating a separate single function that does the same thing as the original two.
The other alternative (list(map(''.join, map(sorted, words)))
) isn't much better; although map(f∘g, x)
is generally equivalent in effect to map(f, map(g, x))
, now you are iterating over the sequence twice (or rather, iterating over one sequence, then iterating over a second intermediate sequence).
CodePudding user response:
If it doesn't already have a name, you need to define the function that you want to map over the list.
You can define a function either with def
, or with lambda
.
words = ["yo", "act", "flop",'tac']
def f(w):
return ''.join(sorted(w))
print( list(map(f, words)) )
# ['oy', 'act', 'flop', 'act']
print( list(map(lambda w: ''.join(sorted(w)), words)) )
# ['oy', 'act', 'flop', 'act']
CodePudding user response:
You can also use join in the map function call:
words = list(map(lambda x: "".join(sorted(x)),words))
print(words)
>>> ['oy', 'act', 'flop', 'act']