What are the common ways to write Pythonic
This article mainly introduces the common Pythonic writing methods, which have a certain reference value, interested friends can refer to, I hope you can learn a lot after reading this article, the following let the editor take you to understand it.
1. Exchange assignment
# # not recommended temp = aa = bb = a # # recommend a, b = b, Mr. a # become a tuple object, and then unpack
2. Unpacking
# # not recommended l = [David', 'Pythonista',' + 1,514,555-1234'] first_name = l [0] last_name = l [1] phone_number = l [2] # # recommended l = [David', 'Pythonista',' + 1,514,555-1234'] first_name, last_name, phone_number = 1 # Python 3 Onlyfirst, * middle, last = another_list
3. Use the operator in
# # not recommended if fruit = = "apple" or fruit = = "orange" or fruit = = "berry": # multiple judgments # # recommend if fruit in ["apple", "orange", "berry"]: # using in is more concise
4. String operation
# # colors = ['red',' blue', 'green',' yellow'] result =''for s in colors: result + = s # discard the previous string object for each assignment and generate a new object # # recommended colors = [' red', 'blue',' green', 'yellow'] result =' '.join (colors) # No additional memory allocation
5. List of dictionary key values
# # for key in my_dict.keys (): # my_ keys [key]. # # recommended for key in my_dict: # my_ keys [key]. # only when the key value needs to be changed in the loop, we need to use my_dict.keys () # to generate a static list of key values.
6. Dictionary key value judgment
# # not recommended if my_dict.has_key (key): #... do something with d [key] # # recommended if key in my_dict: #... do something with d [key]
7. Dictionary get and setdefault methods
# # navs = {} for (portfolio, equity, position) in data: if portfolio not in navs: navs [portfolio] = 0 navs [portfolio] + = position * prices [equity] # # recommended navs = {} for (portfolio, equity, position) in data: # use get method navs [portfolio] = navs.get (portfolio, 0) + position * prices [equity] # or setdefault method navs.setdefault (portfolio, 0) navs [portfolio] + = position * prices [equity]
8. Judge whether it is true or false
# # if x = = True: #.... if len (items)! = 0: #... if items! = []: #... # # recommend if x: #.... if items: #...
9. Traversing lists and indexes
# # items = 'zero one two three'.split () # method 1i = 0for item in items: print I, item I + = method 2for i in range (len (items)): print I, items [I] # # recommended items =' zero one two three'.split () for I, item in enumerate (items): print I, item
10. List derivation
# # not recommended new_list = [] for item in a_list: if condition (item): new_list.append (fn (item)) # # recommended new_list = [fn (item) for item in a_list if condition (item)]
11. List derivation-nesting
# # for sub_list in nested_list: if list_condition (sub_list): for item in sub_list: if item_condition (item): # do something... is not recommended # # recommended gen = (item for sl in nested_list if list_condition (sl)\ for item in sl if item_condition (item)) for item in gen: # do something...
twelve。 Loop nesting
# # not recommended for x in x_list: for y in y_list: for z in z_list: # do something for x & y # # recommended from itertools import productfor x, y, z in product (x_list, y_list, z_list): # do something for x, y, z
13. Try to use generators instead of lists
# # def my_range (n): I = 0 result = [] while I is not recommended
< n: result.append(fn(i)) i += 1 return result # 返回列表##推荐def my_range(n): i = 0 result = [] while i < n: yield fn(i) # 使用生成器代替列表 i += 1*尽量用生成器代替列表,除非必须用到列表特有的函数。 14. 中间结果尽量使用imap/ifilter代替map/filter ##不推荐reduce(rf, filter(ff, map(mf, a_list)))##推荐from itertools import ifilter, imapreduce(rf, ifilter(ff, imap(mf, a_list)))*lazy evaluation 会带来更高的内存使用效率,特别是当处理大数据操作的时候。 15. 使用any/all函数 ##不推荐found = Falsefor item in a_list: if condition(item): found = True breakif found: # do something if found... ##推荐if any(condition(item) for item in a_list): # do something if found... 16. 属性(property) =##不推荐class Clock(object): def __init__(self): self.__hour = 1 def setHour(self, hour): if 25 >Hour > 0: self.__hour = hour else: raise BadHourException def getHour (self): return self.__hour## recommends class Clock (object): def _ init__ (self): self.__hour = 1 def _ setHour (self, hour): if 25 > hour > 0: self.__hour = hour else: raise BadHourException def _ getHour (self): return self.__hour hour = property (_ _ getHour, _ _ setHour)
17. Use with to handle file opening
# # f = open ("some_file.txt") try: data = f.read () # other file operations. Finally: f.close () # # recommend with open ("some_file.txt") as f: data = f.read () # other file operations.
18. Ignore exceptions using with (Python 3 only)
# # try is not recommended: os.remove ("somefile.txt") except OSError: pass## recommends from contextlib import ignored # Python 3 onlywith ignored (OSError): os.remove ("somefile.txt")
19. Use with to handle locking
# # import threadinglock = threading.Lock () lock.acquire () try: # mutually exclusive operation... finally: lock.release () # # recommended import threadinglock = threading.Lock () with lock: # mutually exclusive operation. Thank you for reading this article carefully. I hope the article "what are the common ways to write Pythonic" shared by the editor will be helpful to you. At the same time, I also hope you will support us and pay attention to the industry information channel. More related knowledge is waiting for you to learn!