程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Code anatomy - write high-performance Python code

編輯:Python

Write short and efficient Python Code is not always that easy or straightforward . However , We often see a piece of code , But they are not aware of the thinking process behind the way they are written . We'll look at the clip , It returns the difference between two iterations , To understand its structure .

According to the description of segment function , We can write this naively :

def difference(a, b):
return [item for item in a if item not in b]

This implementation may work well , But don't consider b.  If there are many duplicates in the second list , This makes the code take more time . To solve this problem , We can use set() Methods that keep only the unique values in the list :

def difference(a, b):
return [item for item in a if item not in set(b)]

Although this version looks like an improvement , But it may actually be slower than previous versions . If you look closely , You'll find that set() Every time I call everyitem Lead to a result set(b) Assessed . This is an example , We set() Wrap in another way to better present the problem :

def difference(a, b):
return [item for item in a if item not in make_set(b)]
def make_set(itr):
print('Making set...')
return set(itr)
print(difference([1, 2, 3], [1, 2, 4]))
# Making set...
# Making set...
# Making set...
# [3]

The solution to this problem is set() Call once before list derivation and store results to speed up processing :

def difference(a, b):
_b = set(b)
return [item for item in a if item not in _b]

Another option worth mentioning in terms of performance is to use list derivation and filter()and list(). Using the latter option to implement the same code will result in the following :

def difference(a, b):
_b = set(b)
return list(filter(lambda item: item not in _b, a))

Use timeit Analyze the performance of the last two code examples , It is clear that using list derivation can be ten times faster than the alternative method . This is because it is a native language feature , It works very much like a simple cycle ,for There is no overhead of extra function calls . This explains why we like it better , Besides readability .


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved