1. 程式人生 > >python推導式,匿名函式lambda,生成器

python推導式,匿名函式lambda,生成器

1、推導式

  • 列表推導式,一個表示式構造一個新列表
    [expforitemincollectionifcondition]
    exp列表中的元素
In [188]: %%timeit
   .....: #普通方法
   .....: result1 = []
   .....: for i in range(10000):
   .....:     if i%2 == 0:
   .....:         result1.append(i)
   .....: 

1000 loops, best of 3: 1.06 ms per loop

In [189]: %%timeit
   .....: #列表推導式方法
   .....: result2 = [i for i in range(10000) if i%
2 == 0] .....: 1000 loops, best of 3: 846 µs per loop In [202]: str_lst = ['Welcome', 'to', 'Python', 'Data', 'Analysis', 'Course'] In [203]: result3 = [x.upper() for x in str_lst if len(x) > 4] In [204]: result3 Out[204]: ['WELCOME', 'PYTHON', 'ANALYSIS', 'COURSE']
  • 字典推導式
    {key_exp:value_expfori
    temincollectionincondition}
In [192]: dict1 = {key : value for key, value in enumerate(reversed(range(10))) if key >5}

In [193]: dict1
Out[193]: {6: 3, 7: 2, 8: 1, 9: 0}
  • 集合推導式
    {expforitemincollectionifcondition}
In [200]: set1 = {i+1 for i in range(10) if i > 5}

In [201]: set1
Out[201]: {7, 8
, 9, 10}

2、匿名函式lambda

str_lst = ['Welcome', 'to', 'Python', 'Data', 'Analysis', 'Course']
str_lst.sort(key=lambda x:len(x)) # sort by length
print str_lst

str_lst.sort(key=lambda x:x[-1]) # sort by the last letter
print str_lst