交换两个变量避免使用临时变量
在python中交换变量没有任何理由需要使用临时变量。我们可以使用元组,使我们的意图更加清晰。
不好的写法
temp
= foo
foo = bar
bar = temp
惯用的
(foo, bar) = (bar, foo)
使用元组来分配参数
在python中,能够实现多个元素同时赋值。
不好的写法
list_from_comma_separated_value_file = ['dog', 'Fido', 10]
animal = list_from_comma_separated_value_file[0]
name = list_from_comma_separated_value_file[1]
age = list_from_comma_separated_value_file[2]
惯用的
list_from_comma_separated_value_file = ['dog', 'Fido', 10]
(animal, name, age) = list_from_comma_separated_value_file
使用“.join”来连接一个单独的字符串列表中的元素
它的速度更快,使用更少的内存,你会看到它无处不在。需要注意的是两个单引号表示我们创建的字符串列表元素之间的分隔符。
不好的写法
result_list = ['True', 'False', 'File not found']
result_string = ''
for result in result_list:
result_string += result
惯用的
result_list = ['True', 'False', 'File not found']
result_string = ''.join(result_list)
在dict.get()中使用默认值
经常被忽视的get()的定义是默认的参数。如果不使用默认值(或collections.defaultdict类),你的代码将充斥着混乱。请记住,争取清晰。
不好的写法
log_severity = None
if 'severity' in configuration:
log_severity = configuration['severity']
else:
log_severity = log.Info
惯用的
log_severity = configuration.get('severity', log.Info)
使用上下人管理,以确保资源得到妥善管理
不好的写法
file_handle = open(path_to_file, 'r')
for line in file_handle.readlines():
if some_function_that_throws_exceptions(line):
# do something
file_handle.close()
惯用的
with open(path_to_file, 'r') as file_handle:
for line in file_handle:
if some_function_that_throws_exceptions(line):
# do something
# No need to explicitly call 'close'. Handled by the File context manager
在复合的if语句中避免重复的变量名
当一个人想要检查的一些值,反复列出正在检查的变量,它的值是不必要的冗长。使用临时集合的意图明显。
不好的写法
if name == 'Tom' or name == 'Dick' or name == 'Harry':
is_generic_name = True
惯用的
if name in ('Tom', 'Dick', 'Harry'):
is_generic_name = True
使用列表解析创建现有现有数据的子集列表
不好的写法
some_other_list = range(1, 100)
my_weird_list_of_numbers = list()
for element in some_other_list:
if is_prime(element):
my_weird_list_of_numbers.append(element+5)
惯用的
some_other_list = range(1, 100)
my_weird_list_of_numbers = [element + 5 for element in some_other_list if is_prime(element)]