十个提高代码效率的python技巧

来自blog

namedtuple

If you are too lazy to create a class but you still want to use a variable that can act as a class object, then you should use namedtuple:

from collections import namedtuple
user = namedtuple('u', [1, 2, 3])
ztq = user(a='a', b='b',c='c')
print(ztq.a, ztq.b, ztq.c)

result:

(1,2,3)

decorator

If you are too lazy to change a function from inner code but you still want to add some new features to a function, you should use decorator. For example, if you want to print “hello” when you add two numbers:

def hello(fn):
    def wrapper(*args, **kwargs):
        aa = fn(*args, **kwargs)   
        print('hello')             
        return aa                  
    return wrapper
                                        
def my_add(a,b):
    return a+b
my_add = hello(my_add)
                                                               
aa = my_add(10,10)
print(aa)

result:

hello
20

or you can use operator “@” to implement your function elegantly:

def hello(fn):
    def wrapper(*args, **kwargs):
        aa = fn(*args, **kwargs)   
        print('hello')             
        return aa                  
    return wrapper
                                        
@hello
def my_add(a,b):
    return a+b
                                                               
aa = my_add(10,10)
print(aa)

enumerate

If you are too lazy to count the index of a list in a loop but you still need the index, then you shoud use enumerate:

a = ['a', 'b', 'c']
for ind, item in a:
	print(ind, item)

result:

(0, 'a')
(1, 'b')
(2, 'c')

iterator

If you are too lazy to get the every elements in a list by index or “for” loop but you still need to get every element in order, then you should use iterator:

def inc():
    for i in range(10):
        yield i        
x = inc()
                       
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))

result:

0
1
2
3
4
5
6
7

Do not easily copy object in python

If you are too lazy to get deepcopy a other oject but you still want get a copy of a exists one, then you many creating a bug in you program!
In python, all things are objects, even class is a kind of object. If you want to copy a object another object, then the ID of two objects are same which means the two objects are. If you modify one object, then another object are also modified.

class sample:
   def __init__(self, items = []):
       self.items = items            
                                     
   def append(self, value):
       self.items.append(value)      
                                     
s1 = sample(items=['1'])
s2 = s1
s1.append('a')
s2.append('b')
                                     
print(s1.items, s2.items)

result:

(['1', 'a', 'b'], ['1', 'a', 'b'])

another example:

a = [1,2,3,4]
b = a
b[0] = 100
print(a)
print(b)

result:

[100,2,3,4]
[100,2,3,4]

Instead, you should use “deepcopy” to copy two objects

a = [1,2,3,4]
b = copy.deepcopy(a)
b[0] = 100
print(a)
print(b)

result:

[1,2,3,4]
[100,2,3,4]

itertools

If you are too lazy to write a infinite loop in an iterator but you still want to reset to loop in iterator, then you should use itertools:

import itertools
                                                
def inc():
    a = [1,2,3,4,5]
    cs = itertools.cycle(a) 
    for i in cs:
        yield i             
x = inc()
                            
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))
print(next(x))

result:

1
2
3
4
5
1
2
3

concurrent.futures

If you are too lazy to write a multi-thread to process all the elements of a list which may cost lots of time, then you should use a python build-in multi-thread tools:

import concurrent.futures
def print_num(num):
    print(num)
                                                          
a = range(5)
with concurrent.futures.ProcessPoolExecutor() as executor:
    executor.map(load_and_resize, a)

result:

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值