能提高编程效率的Python小技巧

> Python有很多小技巧可以帮助我们更好更快的写出Pythonic的程序。

交换两个变量的值

a, b = 'abc', 123
print(a, b)  # out: abc 123
b, a = a, b
print(a, b)  # out: 123, abc

优雅的多行字符串

先说最优雅的方法:

sql = ('select * from table_1 '
          'where id > 10 '
          'limit 20')
print(sql)
# out: select * from table_1 where id > 10 limit 20

另外有两种不优雅的方法,一个是行尾加反斜杠,一个是三引号,这两种方法都不支持缩进,如果加了缩进,缩进的空格或tab健也会被算入字符串内:

s1 = 'abc
        123'
print(s1)  # out: abc    123
#缩进也被当做字符串s1的一部分了, 🙁

s2 = ”’abc
123”’

print(s2) # out: abcn      123
#不只是缩进,换行也被当做s2的一部分了, 🙁

s3 = (‘abc’
‘123’)
print(s3)  # out: abc123
#完美!

三元运算符进行条件赋值

这是一个if-else操作的快捷方式:

[表达式为真的返回值] if [表达式] else [表达式为假的返回值]

x, y = 2,3
a = x if y > 4 else y
print(a) # out: 3

字符串反转

s = 'abcdefg'
b = s[::-1]
print(b)  # out: gfedcba

去掉list里面的重复项

ls = [1,2,3,3,3,4]
ls2 = list(set(ls))
#ls2: [1,2,3,4]

字符串/列表/tuple的负数索引

s = 'abc'
s[-1] # c
ls = [1,2,3,4,5,6]
ls[-2] # 5

列表展开

In [25]: import itertools

In [26]: a = [[1,2], [3,4], [5,6]]

In [27]: list(itertools.chain.from_iterable(a))
Out[27]: [1, 2, 3, 4, 5, 6]

In [28]: sum(a, [])
Out[28]: [1, 2, 3, 4, 5, 6]

In [29]: [x for l in a for x in l]
Out[29]: [1, 2, 3, 4, 5, 6]

反转字典

In [30]: m = {'a': 1, 'b': 2, 'c': 3, 'd': 4}

In [31]: m
Out[31]: {‘a’: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}

In [32]: {v: k for k, v in m.items()}
Out[32]: {1: ‘a’, 2: ‘b’, 3: ‘c’, 4: ‘d’}

集合的操作

In [33]: A = {1,2,3,3}

In [34]: A
Out[34]: {1, 2, 3}

In [35]: B = {3,4,5,6,7}

In [36]: B
Out[36]: {3, 4, 5, 6, 7}

In [37]: A | B
Out[37]: {1, 2, 3, 4, 5, 6, 7}

In [38]: A & B
Out[38]: {3}

In [39]: A – B
Out[39]: {1, 2}

In [40]: B – A
Out[40]: {4, 5, 6, 7}

In [41]: A ^ B
Out[41]: {1, 2, 4, 5, 6, 7}

排序的key

sort()函数可以指定key或cmp函数,最好使用key,据说速度更快

In [42]: s = [(1,3,5), (3,4,7), (9,0,4)]

In [43]: s.sort(key=lambda a: a[0])

In [44]: s
Out[44]: [(1, 3, 5), (3, 4, 7), (9, 0, 4)]

In [45]: s.sort(key=lambda a: a[1])

In [46]: s
Out[46]: [(9, 0, 4), (1, 3, 5), (3, 4, 7)]

in的使用

In [47]: 'a' in 'abc'
Out[47]: True

In [48]: ‘e’ not in ‘abc’
Out[48]: True

In [49]: 5 in [1,2,3,4]
Out[49]: False

In [50]: ‘k’ in {‘a’: 1, ‘k’: 3}
Out[50]: True

In [51]: ‘s’ in {‘a’, ‘b’, ‘c’}
Out[52]: False

while 1 比 while True 更快

使用C实现的cPickle, cStringIO替代Pickle, StringIO

未经允许不得转载:996ICU » 能提高编程效率的Python小技巧

赞 (0) 打赏