python高效实用方法

1.斐波那契数列(生兔子问题)

In [1]: def fib(n):
   ...:     a = 1
   ...:     b = 1
   ...:     for i in range(n):
   ...:         yield a
   ...:         a,b = b,a+b
   ...:         

In [2]: num = fib(5)

#报错
In [3]: num.next()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
 in ()
----> 1 num.next()

AttributeError: 'generator' object has no attribute 'next'

#使用__next__()
In [6]: num.__next__()
Out[6]: 1

In [7]: num.__next__()
Out[7]: 1

In [8]: num.__next__()
Out[8]: 2

In [9]: num.__next__()
Out[9]: 3

In [10]: num.__next__()
Out[10]: 5

In [11]: num.__next__()
---------------------------------------------------------------------------
StopIteration                             Traceback (most recent call last)
 in ()
----> 1 num.__next__()

StopIteration:

2.三元运算符 lambda表达式

#为真时的结果 if 判定条件 else 为假时的结果 
In [19]: 4 if 4>5 else 5
Out[19]: 5
#lambda表达式
In [12]: (lambda x:x+x)(5)
Out[12]: 10
In [13]: (lambda x,y:x+y)(2,5)
Out[13]: 7

3.filter过滤器函数 (python2中直接返回一个List/String/Tuple,python3中返回迭代器对象,可用list(filter())转换)

In [26]: def f(x):return x%2!=0 and x%3!=0

In [27]: filter(f,range(2,25))
Out[27]: 

In [28]: g = filter(f,range(2,25))

In [29]: g.__next__()
Out[29]: 5

In [30]: g.__next__()
Out[30]: 7

In [31]: g.__next__()
Out[31]: 11

In [32]: g.__next__()
Out[32]: 13

In [33]: list(g)
Out[33]: [17, 19, 23]

4.map函数(为列表推导式[f(x) for x in iterable])

In [43]: def f(x,y):
    ...:     return (x,y)  
  
In [37]: x = [1,3,5,7,9]
In [38]: y = ['a','b','c','d','e']


In [44]: map(f,x,y)
Out[44]: 

In [45]: g = map(f,x,y)

In [46]: g.__next__()
Out[46]: (1, 'a')

In [47]: g.__next__()
Out[47]: (3, 'b')

In [48]: list(g)
Out[48]: [(5, 'c'), (7, 'd'), (9, 'e')]

In [50]: g = map(f,x,y)

In [51]: dict(g)
Out[51]: {1: 'a', 3: 'b', 5: 'c', 7: 'd', 9: 'e'}

5.reduce函数

In [52]: from functools import reduce

In [53]: l = [0,1,2,3,4,5,6]

In [54]: def f(x,y):
    ...:     return (x+y)
  
In [55]: reduce(f,l)
Out[55]: 21

6.zip函数[转化字典可dict(zip())]

In [56]: x = [1,2,3]

In [57]: y = [4,5,6]

In [58]: z = [7,8,9]

In [59]: xyz = zip(x,y,z)

In [60]: xyz
Out[60]: 

In [61]: list(xyz)
Out[61]: [(1, 4, 7), (2, 5, 8), (3, 6, 9)]

#zip和*zip
In [13]: x = [1,2,3]

In [14]: y = ["a","b","c"]

In [15]: z = ["一","二","三"]

In [16]: zipa = list(zip(x,y,z))

In [17]: list(zipa)
Out[17]: [(1, 'a', '一'), (2, 'b', '二'), (3, 'c', '三')]

In [18]: list(zip(*zipa))
Out[18]: [(1, 2, 3), ('a', 'b', 'c'), ('一', '二', '三')]


7.列表推导式


In [36]: l = [1,2,3,4,5,6,7,8,9]

In [37]: [x*2 for x in l if x>2]
Out[37]: [6, 8, 10, 12, 14, 16, 18]

In [39]: dict([(x,x*2) for x in l])
Out[39]: {1: 2, 2: 4, 3: 6, 4: 8, 5: 10, 6: 12, 7: 14, 8: 16, 9: 18}

8.字典推导式

In [48]: d = {x:x*2 for x in range(1,5)}

In [49]: d
Out[49]: {1: 2, 2: 4, 3: 6, 4: 8}

9.集合推导式(去重)

In [50]: l = [1,2,4,5,7,3,2,4,6,2,4,6]

In [51]: s = {x for x in l}

In [52]: s
Out[52]: {1, 2, 3, 4, 5, 6, 7}

10.计数器功能(和词频统计差不多)

In [53]: from collections import Counter

In [54]: c = Counter("Hello world")

In [55]: c
Out[55]: Counter({'H': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1})
#找出出现次数最多的前一个
In [56]: c.most_common(1)
Out[56]: [('l', 3)]
#找出出现次数最多的前两个
In [57]: c.most_common(2)
Out[57]: [('l', 3), ('o', 2)]

11.sort和sorted

#sort
In [4]: x = [2,1,4,6,7,3,2,1]
In [5]: x.sort()
In [6]: x
Out[6]: [1, 1, 2, 2, 3, 4, 6, 7]

#sorted
In [7]: sorted("Hello world")
Out[7]: [' ', 'H', 'd', 'e', 'l', 'l', 'l', 'o', 'o', 'r', 'w']
#按照l第三个数进行排序(默认由小到大)
In [8]: l = [(1,4,2),(2,4,3),(4,2,5)]
In [12]: sorted(l,key=lambda l:l[2])
Out[12]: [(1, 4, 2), (2, 4, 3), (4, 2, 5)]
#reverse=False默认为由小到大升序
#reverse=True默认为由大到小降序
In [13]: sorted(l,key=lambda l:l[2],reverse=True)
Out[13]: [(4, 2, 5), (2, 4, 3), (1, 4, 2)]
#python3中使用cmp会报错,建议使用key
In [14]: sorted(l, cmp=lambda x : cmp(x[2]))
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
 in ()
----> 1 sorted(l, cmp=lambda x : cmp(x[2]))

TypeError: 'cmp' is an invalid keyword argument for this function

#可使用itemgetter进行多级排序
In [15]: from operator import itemgetter, attrgetter 
#按照第三个数进行排序
In [16]: sorted(l, key=itemgetter(2))
Out[16]: [(1, 4, 2), (2, 4, 3), (4, 2, 5)]
#先按照第二个数进行排序,再按照第一个数进行排序
In [19]: sorted(l, key=itemgetter(1,0))
Out[19]: [(4, 2, 5), (1, 4, 2), (2, 4, 3)]
#对字典排序,排序后转化为list
In [20]: d = {"a":1,"b":3,"c":2}
In [22]: sorted(d.items(),key = itemgetter(1),reverse=True)
Out[22]: [('b', 3), ('c', 2), ('a', 1)]
#元组不可转为字典

12.切片[起始位置:结束位置:步长值(默认1)]

#切片的结果起始位置为下标,结束位置为下标的前一位
In [23]: l = [0,1,2,3,4,5]
In [24]: l[1:5]
Out[24]: [1, 2, 3, 4]

#当切片超出范围时不报错,取到最后一位
In [25]: l[1:7]
Out[25]: [1, 2, 3, 4, 5]

#设置步长为2
In [26]: l[1:5:2]
Out[26]: [1, 3]

#倒叙
In [27]: l[::-1]
Out[27]: [5, 4, 3, 2, 1, 0]

#取偶数
In [32]: l[::2]
Out[32]: [0, 2, 4]

#取奇数
In [33]: l[1::2]
Out[33]: [1, 3, 5]

#取倒叙
In [29]: l[-2:-5:-1]
Out[29]: [4, 3, 2]


In [31]: l[-5:-2]
Out[31]: [1, 2, 3]

你可能感兴趣的:(python高效实用方法)