How's my list comprehension? - Printable Version +- Python Forum (https://python-forum.io) +-- Forum: General (https://python-forum.io/forum-1.html) +--- Forum: Code sharing (https://python-forum.io/forum-5.html) +--- Thread: How's my list comprehension? (/thread-15479.html) |
How's my list comprehension? - Clunk_Head - Jan-18-2019 I'm just having fun, but can it be done better? oob = lambda name: ''.join([letter if letter not in "aeiouAEIOU" else "oob" for letter in name]) oob("Name")Outputs >>>"Noobmoob" RE: How's my list comprehension? - nilamo - Jan-18-2019 Maybe a translation table? >>> mapping = str.maketrans({letter: "oob" for letter in "aeiou"}) >>> oob = "nilamo".translate(mapping) >>> oob 'noobloobmoob'Or a regular expression: >>> import re >>> re.sub("[aeiou]", "oob", "nilamo") 'noobloobmoob' RE: How's my list comprehension? - ichabod801 - Jan-18-2019 That's a bad use of lambda. You should only use lambda for single use functions passed as a parameter. Otherwise define a function. Here's a better use of lambda for this case: oob = ''.join(map(lambda letter: 'oob' if letter.lower() in 'aeiou' else letter, 'Ichabod')) RE: How's my list comprehension? - Clunk_Head - Jan-18-2019 (Jan-18-2019, 11:32 PM)ichabod801 Wrote: That's a bad use of lambda. You should only use lambda for single use functions passed as a parameter. Otherwise define a function. Here's a better use of lambda for this case: Granted, but that's not what I asked about. RE: How's my list comprehension? - Clunk_Head - Jan-19-2019 (Jan-18-2019, 10:41 PM)nilamo Wrote: Or a regular expression:>>> import re >>> re.sub("[aeiou]", "oob", "nilamo") 'noobloobmoob' I like this one the best |