专栏名称: AI科技大本营
迎来到AI科技大本营。这里汇集了优秀的AI学习者,技术大咖和产业领袖;提供接地气的实战课程。在这里和优秀的人一起成长。
目录
相关文章推荐
爱可可-爱生活  ·  【[185星]CM6_COBOT_ROBOT ... ·  2 天前  
爱可可-爱生活  ·  【[540星]AgentQL:AI驱动的网页 ... ·  2 天前  
黄建同学  ·  这款Synthesis ... ·  3 天前  
爱可可-爱生活  ·  【[9.2k星]Wave ... ·  3 天前  
51好读  ›  专栏  ›  AI科技大本营

优雅编写Python3的62个小贴士!

AI科技大本营  · 公众号  · AI  · 2019-07-30 19:02

正文


作者 | QIML编辑部

来源 | 量化投资与机器学习(ID:Lhtz_Jqxx)


今天公众号为大家带来一篇有关Python技巧的文章,可以帮助你编写优雅的Python3代码!


iterable技巧


1、创建一个数字序列(从0到10,间隔为2)


>>> range(0,10,2)
[02468]


2、对一串数字求和( 从0到10,间隔为2


>>> l = range(0,10,2)
>>> sum(l)
20


3、检查序列中的任一元素是否为True


>>> any(a % 2 for a in range(0,10,2))
True


4、检查序列中的所有元素是否为True


>>> all(a % 2 for a in range(0,10,2))
True


5、累计求和一串数字序列


>>> import numpy as np
>>> res = list(np.cumsum(range(0,10,2)))
>>> res
0261220]


6、给定每个iterable,通过添加索引来构造一个元组


>>> a = ['Hello''world''!']
>>> list(enumerate(a))
[(0'Hello'), (1'world'), (2'!')]


7、将iterable连接到单个字符串


>>> a = ["python","really""rocks"]
>>> " ".join(a)
'python really rocks'


8、组合两个可迭代的元组或pivot嵌套的iterables


# Combining two iterables
>>> a = [123]
>>> b = ['a''b''c']
>>> z = zip(a, b)
>>> z
[(1'a'), (2'b'), (3'c')]

# Pivoting list of tuples
>>> zip(*z)
[(123), ('a''b''c')]


9、从 iterables 中获取最小值/最大值(具有/不具有特定功能)


# Getting maximum from iterable
>>> a = [12-3]
>>> max(a)
2

# Getting maximum from iterable
>>> min(a)
1

# Bot min/max has key value to allow to get maximum by appliing function
>>> max(a,key=abs)
3


10、可迭代排序(可以通过“compare”函数排序)


>>> a = [12-3]
>>> sorted(a)
[-312]

>>> sorted(a,key=abs)
[12-3]


11、将单个字符串拆分为列表


>>> s = "a,b,c"
>>> s.split(",")
["a""b""c"]


12、初始化一个包含重复数字的列表


>> [1]* 10
[1111111111]


13、合并/插入两个字典


>>> a = {"a":1"b":1}
>>> b = {"b":2"c":1}
>>> a.update(b)
>>> a
{"a":1"b":2"c":1}


14、命名和保存 iterables 切片


# Naming slices (slice(start, end, step))
>>>  a = [012345]
>>> LASTTHREE = slice(-3None)
>>> LASTTHREE
slice(-3NoneNone)
>>> a[LASTTHREE]
[345]


15、在列表中查找项的索引


>>> a = ["foo""bar""baz"]
>>> a.index("bar")
1


16、在 iterables 中查找最小/最大项的索引


>>> a = [231]
>>> min(enumerate(a),key=lambda x: x[1])[0]
2


17、 iterables的k个元素


>>> a = [1234]
>>> k = 2
>>> a[-2:] + a[:-2]
[3412]


18、删除字符串末尾/开始/两端无用的字符


>>> name = "//George//"
>>> name.strip("/")
'George'
>>> name.rstrip("/")
'//George'
>>> name.lstrip("/")
'George//'


19、倒序 iterables 的顺序(字符串、列表等)


# Reversing string
>>> s = "abc"
>>> s[::-1]
"cba"

# Reversing list
>>> l = ["a""b""c"]
>>> l[::-1]
["c""b""a"]


branching技巧


20、多个short-cut


>>>  n = 10
>>> 1 < n 20
True


21、For-else结构在搜索某些东西并找到它时很有用


for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")


22、Trenary operator


>>> "Python ROCK" if True else " I AM GRUMPY"
"Python ROCK"


23、Try-catch-else结构


try:
    foo()
except Exception:
    print("Exception occured" )
else:
    print("Exception didnt occur")
finally:
    print("Always gets here")


24、While-else结构


i = 5

while i > 1:
    print("Whil-ing away!")
    i -= 1
    if i == 3:
        break
else:
    print("Finished up!")


comprehensions(推导式)技巧


25、List推导式


>>> m = [x ** 2 for x in range(5)]
>>> m
[014916]


26、Set推导式


>>> m = {x ** 2 for x in range(5)}
>>> m
{014916}


27、Dict推导式


>>> m = {x: x ** 2 for x in range(5)}
>>> m
{00112439416}


28、Generator推导式


# A generator comprehension is the lazy version of a list comprehension.
>>> m = (x ** 2  for x in range(5))
>>> m
at 0x108efe408>
>>> list(m)
[014916]

>>> m = (x ** 2 for x in range(5))
>>> next(m)
0
>>> list(m)
[14916]


▍29、list推导使用当前值和过往值


>>> a = [124,2]
>>> [y - x for x,y in zip(a,a[1:])]
[12-2]


unpacking技巧


30、从iterable解压缩变量


# One can unpack all iterables (tuples, list etc)
>>> a, b, c = 123
>>> a, b, c
(123)

>>> a, b, c = [123]
>>> a, b, c
(123)


31、交换变量值


>>> a, b = 12
>>> a, b = b, a
>>> a, b
(21)


32、在不指示所有元素的情况下从iterable解包变量


>>> a, *b, c = [12345]
>>> a
1
>>> b
[234]
>>> c
5


33、使用splat运算符解包变量


>>> def test(x, y, z):
>>>      print(x, y, z)
>>> res = test(*[102030])
10 20 30
>>> res = test(**{'x'1'y'2'z'3} )
10 20 30 
view raw







Itertools技巧


34、Flatten iterables


>>> a = [[12], [34], [56]]
>>> list(itertools.chain.from_iterable(a))
[123 456]


▍35、从iterables创建笛卡尔积


>>> for p in itertools.product([123], [45]):
>>>      print(''.join(str(x) for x in p))

(14)
(15)
(24)
(25)
(34)
(35)


▍36、从iterable创建排列


>>> for p in itertools.permutations([1234]):
>>>      print(''.join(str(x) for x in p))
123
132
213
231
312
321


▍37、从iterable创建ngram


>>> from itertools import islice
>>> def n_grams(a, n):
...          z = (islice(a, i, Nonefor i in range(n))
...          return zip(*z)
...
>>> a = [123456]
>>> n_grams(a, 3)
[(123), (234), (345), (456)]
>>> n_grams(a, 2)
[(12), (23), (34), (45), (56)]
>>> n_grams(a, 4)
[(12 34), (2345), (3456)]


▍38、使用填充组合元组的两个迭代器或使用填充pivot嵌套迭代


>>> import itertools as it
>>> x = [12345]
>>> y = ['a''b''c']
>>> list(zip(x, y))
[(1'a'), (2'b'), (3'c')]

>>> list(it.zip_longest(x, y))
[(1'a'), (2'b'), (3'c'), (4None), (5None)]


▍39、从一个 iterable n中创建k个组合


>>>  import itertools
>>> bills = [20202010101010105511111]
>>> list(itertools.combinations(bills, 3))
[(202020), (202010), (202010), ... ]


▍40、在给定函数情况下创建一个迭代的累积结果


>>> import itertools
>>> list(itertools.accumulate([921175111226], min))
[999555 22]


▍41、创建一个迭代器,只要谓词为True,就从iterable返回元素


>>> import itertools
>>> itertools.takewhile(lambda x: x 3, [01234])
[012]

>>> it.dropwhile(lambda x: x 3, [01234])
[34]


▍42、创建一个迭代器,它从iterable中过滤元素,只返回谓词为False的元素


>>> import itertools
# keeping only false values
>>> list(itertools.filterfalse(bool, [NoneFalse1010]))
[NoneFalse0]


使用从迭代的迭代中获得的参数来计算函数


>>>  import itertools
>>> import operator
>>> a = [(26), (84), (73)]
>>> list(itertools.starmap(operator.mul, a))
[123221]


collections技巧


44、设置基本操作


>>> A = {1233}
>>> A
set([123])
>>> B = {34567}
>>> B
set([34567])
>>> A | B
set([1234567])
>>> A & B
set([3])
>>> A - B
set([1 2])
>>> B - A
set([4567])
>>> A ^ B
set([124567])
>>> (A ^ B) == ((A - B) | (B - A))
True


45、计数器数据结构(无序集合,其中元素存储为字典键,其计数存储为字典值)


import collections

>>> A = collections.Counter([112233334567])
>>> A
Counter({34122241516171})
>>> A.most_common(1)
[(34)]
>>> A.most_common(3 )
[(34), (12), (22)]


46、默认字典结构(字典的子类,在访问不存在的键时检索默认值)


>>> import collections
>>> m = collections.defaultdict(int)
>>> m['a']
0

>>> m = collections.defaultdict(str)
>>> m['a']
''
>>> m['b'] += 'a'
>>> m['b']
'a'

>>> m = collections.defaultdict(lambda'[default value]')
>>> m['a']
'[default value]'
>>> m['b']
'[default value]'

>>> m = collections.defaultdict(list)
>>> m['a']
[]


47、有序的dict结构(保持有序字典的子类)


>>> from  collections import OrderedDict

>>> d = OrderedDict.fromkeys('abcde')
>>> d.move_to_end('b')
>>> ''.join(d.keys())
'acdeb'

>>> d.move_to_end('b', last=False)
>>> ''.join(d.keys())
'bacde'


48、Deques结构(Deques是堆栈和队列的概括)


>>> import collection
>>> Q = collections.deque()
>>> Q.append(1)
>>> Q.appendleft(2)
>>> Q.extend([34])
>>> Q.extendleft([56])
>>> Q
deque([652134])
>>> Q.pop()
4
>>> Q.popleft()
6
>>> Q
deque([521







请到「今天看啥」查看全文