2018-04-14 开胃学习Python系列 - Lambda
2018-04-14 本文已影响0人
Kaiweio
Lambda and List Comprehensions
对lambda这个内容,我一直也是能看到,但是没有总结过,今天顺便把这个部分内容也总结一下。
my_function = lambda a, b, c : a + b
my_function(1, 2, 3)
>>> 3
people = ['Dr. C Brooks', 'Dr. K Collins-Thompson', 'Dr. VG Vydiswaran', 'Dr. D 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 x: x.split()[0] + ' ' + x.split()[-1])(person))
#option 2
list(map(split_title_and_name, people))
== list(map(lambda x: x.split()[0] + ' ' + x.split()[-1], people))
# 输出都是true
顺便讲一个 List Comprehensions
def times_tables():
lst = []
for i in range(10):
for j in range (10):
lst.append(i*j)
return lst
times_tables() == [j*i for i in range(10) for j in range(10)]
lowercase = 'abcdefghijklmnopqrstuvwxyz'
digits = '0123456789'
correct_answer = [a+b+c+d for a in lowercase for b in lowercase for c in digits for d in digits]
correct_answer[:50] # Display first 50 ids