I found this code example, which I think is very well written, but I'm having trouble understanding why part of it works.
The code searches for the longest word in a string:
def LongestWord(str):
''.join(map(lambda x: [' ',x][x.isalnum()], str)).split()
I have no idea how [' ',x][x.isalnum()] works. Does this construction have a name?
break it into 2 parts...
[' ', x]
builds a list of 2 elements. re-write as:
lst = [' ', x]
lst[x.isalnum()]
Now we see that the second brackets are to index the list created by the first brackets. Since str.isalnum() returns a boolean (True or False) and since booleans behave like integers in python (True -> 1, False -> 0), then the construction just picks one of the two elements in the list.
Note that these days (python2.5 and later), it is more idiomatic (and probably more efficient) to use a conditional expression:
lambda x: x if x.isalnum() else ' '
The key to understanding this code is to know that boolean values can be used to index lists.
['a','b'][True] # produces 'b'
['a','b'][False] # produces 'a'
so the code
[' ',x][x.isalnum()]
will produce x if x is alpha-numeric otherwise it will produce ' '
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With