Python 語法基礎 lambda, list comprehensions
阿新 • • 發佈:2018-12-23
lambda
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
a=[]
for person in people:
print(split_title_and_name(person) == (lambda x: x.split()[0] + ' ' + x.split()[-1])(person))
a.append((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))
Let's iterate from 0 to 999 and return the even numbers.
List Comprehensions
my_list = []
for number in range(0, 1000):
if number % 2 == 0:
my_list.append(number)
my_list
Now the same thing but with list comprehension.
my_list = [number for number in range(0,1000) if number % 2 == 0]
my_list