Python Forum
How's my list comprehension?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How's my list comprehension?
#1
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"
[Image: 50337809_1143130745880257_74678398887426...e=5CC6C909]
Reply
#2
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'
Reply
#3
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'))
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#4
(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:

oob = ''.join(map(lambda letter: 'oob' if letter.lower() in 'aeiou' else letter, 'Ichabod'))

Granted, but that's not what I asked about.
Reply
#5
(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
Reply


Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020