nanny
nanny

Reputation: 57

Lambda and List Comprehensions in Python

I am taking a DS class using Python where they asked the me to fix the next function. Since I am learning programming in Python parallel to take this class, I am kind of lost any help. Will be appreciated it!

split_title_and_name

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):
    return person.split()[0] + ' ' + person.split()[-1]

#option 1
for person in people:
    print(split_title_and_name(person) == (lambda person:???))

#option 2
#list(map(split_title_and_name, people)) == list(map(???))

Upvotes: 0

Views: 1114

Answers (3)

28Greka
28Greka

Reputation: 11

THIS WORKS(:

people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']

def split_title_and_name(person):
    title = person.split()[0]
    lastname = person.split()[-1]
    return '{} {}'.format(title, lastname)

list(map(split_title_and_name, people))

Upvotes: 0

Abi
Abi

Reputation: 1

list(map(split_title_and_name, people)) == list(map(lambda person: person.split()[0] + ' ' + person.split()[-1], people))

Upvotes: 0

Moinuddin Quadri
Moinuddin Quadri

Reputation: 48037

Based on the name of the function, I think you want this:

>>> people = ['Dr. Christopher Brooks', 'Dr. Kevyn Collins-Thompson', 'Dr. VG Vinod Vydiswaran', 'Dr. Daniel Romero']
>>> def split_title_and_name(people_list):
...     return [p.split('. ') for p in people_list]
...                    # ^ Assuming title will always be followed by dot '.',
                       # There will be only one '.' dot in the sample string

>>> split_title_and_name(people)
[['Dr', 'Christopher Brooks'],
#  ^     ^
# Title  Name 
 ['Dr', 'Kevyn Collins-Thompson'], 
 ['Dr', 'VG Vinod Vydiswaran'], 
 ['Dr', 'Daniel Romero']]

Note: And definitely you do not need lambda over here. It is not needed here in any context.

Upvotes: 1

Related Questions