[英]Lambda and List Comprehensions in Python
I am taking a DS class using Python where they asked the me to fix the next function.我正在使用 Python 参加 DS 课程,他们要求我修复下一个功能。 Since I am learning programming in Python parallel to take this class, I am kind of lost any help.由于我正在并行学习 Python 编程以参加这门课程,因此我失去了任何帮助。 Will be appreciated it!将不胜感激!
split_title_and_name 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(???))
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.注意:这里绝对不需要lambda 。 It is not needed here in any context.在任何情况下,这里都不需要它。
list(map(split_title_and_name, people)) == list(map(lambda person: person.split()[0] + ' ' + person.split()[-1], people))
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))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.