python常用技巧

交换两个变量避免使用临时变量

在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)]




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值