Python一些不为人知的基础技巧

1.startswith()和endswith()参数可以是元组

当检测字符串开头或结尾时,如果有多个检测值,可以用元组作为startswith()endswith()参数:

 1 # bad
 2 if image.endswith('.jpg') or image.endswith('.png') or image.endswith('.gif'):
 3     pass
 4 # good
 5 if image.endswith(('.jpg', '.png', '.gif')):
 6     pass
 7 # bad
 8 if url.startswith('http:') or url.startswith('https:') or url.startswith('ftp:'):
 9     pass
10 # good
11 if url.startswith(('http:', 'https:', 'ftp:')):
12     pass

2.enumerate()设置start参数做为索引起始值 

当用enumerate()迭代同时要得到索引时,可以设置start参数作为索引起始值:

1 # bad
2 for index, v in enumerate(data):
3     print(index+1, v)
4 # good
5 for index, v in enumerate(data, start=1):
6     print(index, v)

3.对切片命名 

当代码中到处都是硬编码的切片索引时,我们的代码将变得无法阅读。可以对切片命名解决此问题:

1 record = '....................100.................513.25......'
2 # bad
3 cost = int(record[20:23]) * float(record[40:46])
4 # good
5 SHARES = slice(20, 23)
6 PRICE = slice(40, 46)
7 cost = int(record[SHARES]) * float(record[PRICE])

作为一条基本准则,代码中如果有很多硬编码的索引值,将导致可读性合可维护性都不佳。一般来说,内置的slice()函数会创建一个切片对象,可以用在任何允许进行切片操作的地方。例如:

 1 >>> items = [0, 1, 2, 3, 4, 5, 6]
 2 >>> a = slice(2, 4)
 3 >>> items[2:4]
 4 [2, 3]
 5 >>> items[a]
 6 [2, 3]
 7 >>> items[a] = [-2, -3]
 8 >>> items
 9 [0, 1, -2, -3, 4, 5, 6]
10 >>> del items[a]
11 >>> items
12 [0, 1, 4, 5, 6]
13 >>>

python学习交流群:125240963

4.上下文管理器可以同时管理多个资源 

假设你要读取一个文件的内容,经过处理以后,写入到另一个文件。你能写出pythonic的代码,所以你使用了上下文管理器,满意地的写出了下面这样的代码:

1 with open('input.txt', 'r') as source:
2     with open('output.txt', 'w') as target:
3         target.write(source.read())

你已经做的很好了,但是上下文管理器可以同时管理多个资源,上面这段代码还可以这样写: 

1 with open('input.txt', 'r') as source, open('output.txt', 'w') as target:
2     target.write(source.read())

5.else子句 

Python中的else子句不仅能在if语句中使用,还能在for、while、和try语句中使用。
在for循环或是while循环正常运行完毕时(而不是通过break语句或是return语句或是异常退出循环),才会运行else块。
举个例子:

 1 >>> for i in range(3):
 2 ...     print(i)
 3 ... else:
 4 ...     print('Iterated over everything')
 5 ... 
 6 0
 7 1
 8 2
 9 Iterated over everything
10 >>>

如上,for循环正常结束,所以运行了后面的else块。 

 1 >>> for i in range(3):
 2 ...     if i == 2:
 3 ...         break
 4 ...     print(i)
 5 ... else:
 6 ...     print('Iterated over everything')
 7 ... 
 8 0
 9 1
10 >>>

由此可以看出,for循环如果没有正常运行完毕(如上面是break结束循环的),是不会运行后面的else块。 

仅当try块中没有异常抛出时才运行else块。一开始,你可能觉得没必要在try/except块中使用else子句。毕竟,在下述代码片段中,只有dangerous_call()不抛出异常,after_call()才会执行,对吧?

1 try2     dangerous_call()
3     after_call()
4 except OSError:
5     log('OSError...')

然而,after_call()不应该放在try块中。为了清晰明确,try块中应该只包括抛出预期异常的语句。因此,向下面这样写更好: 

1 try:
2     dangerous_call()
3 except OSError:
4     log('OSError...')
5 else:
6     after_call()

现在很明确,try块防守的是dangerous_call()可能出现的错误,而不是after_call()。而且很明显,只有try块不抛出异常,才会执行after_call()。但要注意一点,else子句抛出的异常不会由前面的except子句处理,也就是说此时after_call()如果抛出异常,将不会被捕获到。 

python学习交流群:125240963

转载至:http://www.revotu.com/python-some-common-tricks.html#more

猜你喜欢

转载自www.cnblogs.com/pythonedu/p/9058096.html