To write Pythonic (elegant, idiomatic, clean) code, you need to read and learn a lot of Pythonic code. Github has a lot of excellent source code to read, such as Requests, Flask, and Tornado. Here are some common Pythonic scripts.

A program must be understood by a human before it can be executed by a computer.

Programs must be written for people to read, and only incidentally for machines to execute.

1. Swap assignments

# # is not recommended
temp = a
a = b
b = a  

# # to recommend
a, b = b, a  Create a tuple object and unpack it
Copy the code

2. Unpacking

# # is not recommended
l = ['David'.'Pythonista'.'+ 514-555-1234]
first_name = l[0]
last_name = l[1]
phone_number = l[2]  

# # to recommend
l = ['David'.'Pythonista'.'+ 514-555-1234]
first_name, last_name, phone_number = l

# Python 3 Only
first, *middle, last = another_list
Copy the code

3. Use the in operator

# # is not recommended
if fruit == "apple" or fruit == "orange" or fruit == "berry":
    # Multiple judgments

# # to recommend
if fruit in ["apple"."orange"."berry"] :# Use in more succinctly
Copy the code

4. String operations

# # is not recommended
colors = ['red'.'blue'.'green'.'yellow']

result = ' '
for s in colors:
    result += s  Each assignment dismisses the previous string object and generates a new object

# # to recommend
colors = ['red'.'blue'.'green'.'yellow']
result = ' '.join(colors)  # No additional memory allocation
Copy the code

5. Dictionary key list

# # is not recommended
for key in my_dict.keys():
    # my_dict[key] ...

# # to recommend
for key in my_dict:
    # my_dict[key] ...

# use my_dict.keys() only if we need to change the key in the loop
Generate a static list of key values.
Copy the code

6. Dictionary key value judgment

# # is not recommended
if my_dict.has_key(key):
    # ...do something with d[key]  

# # to recommend
if key in my_dict:
    # ...do something with d[key]
Copy the code

7. Dictionary get and setdefault methods

# # is not recommended
navs = {}
for (portfolio, equity, position) in data:
    if portfolio not in navs:
            navs[portfolio] = 0
    navs[portfolio] += position * prices[equity]
# # to recommend
navs = {}
for (portfolio, equity, position) in data:
    Use the get method
    navs[portfolio] = navs.get(portfolio, 0) + position * prices[equity]
    Or use the setdefault method
    navs.setdefault(portfolio, 0)
    navs[portfolio] += position * prices[equity]
Copy the code

8. Determine authenticity

# # is not recommended
if x == True:
    #...
iflen(items) ! =0:
    #...
ifitems ! = [] :#...

# # to recommend
if x:
    #...
if items:
    #...
Copy the code

9. Iterate over lists and indexes

# # is not recommended
items = 'zero one two three'.split()
# method 1
i = 0
for item in items:
    print i, item
    i += 1
# method 2
for i in range(len(items)):
    print i, items[i]

# # to recommend
items = 'zero one two three'.split()
for i, item in enumerate(items):
    print i, item
Copy the code

10. List derivation

# # is not recommended
new_list = []
for item in a_list:
    if condition(item):
        new_list.append(fn(item))  

# # to recommend
new_list = [fn(item) for item in a_list if condition(item)]
Copy the code

11. List derivation – nesting

# # is not recommended
for sub_list in nested_list:
    if list_condition(sub_list):
        for item in sub_list:
            if item_condition(item):
                # do something...  
# # to recommend
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...
Copy the code

12. Loop nesting

# # is not recommended
for x in x_list:
    for y in y_list:
        for z in z_list:
            # do something for x & amp; y

# # to recommend
from itertools import product
for x, y, z in product(x_list, y_list, z_list):
    # do something for x, y, z
Copy the code

13. Use generators instead of lists whenever possible

# # is not recommended
def my_range(n):
    i = 0
    result = []
    whilei & lt; n: result.append(fn(i)) i +=1
    return result  # return list

# # to recommend
def my_range(n):
    i = 0
    result = []
    whilei & lt; n:yield fn(i)  Use generators instead of lists
        i += 1
Use generators instead of lists unless you must use list-specific functions.
Copy the code

14. Try to use IMAP/IFilter instead of Map /filter for intermediate results

# # is not recommended
reduce(rf, filter(ff, map(mf, a_list)))

# # to recommend
from itertools import ifilter, imap
reduce(rf, ifilter(ff, imap(mf, a_list)))
# lazy Evaluation leads to more efficient memory usage, especially when handling large data operations.
Copy the code

15. Use any/all functions

# # is not recommended
found = False
for item in a_list:
    if condition(item):
        found = True
        break
if found:
    # do something if found...  

# # to recommend
if any(condition(item) for item in a_list):
    # do something if found...
Copy the code

16. Properties (property)

# # is not recommended
class Clock(object):
    def __init__(self):
        self.__hour = 1
    def setHour(self, hour):
        if 25& gt; hour & gt;0: self.__hour = hour
        else: raise BadHourException
    def getHour(self):
        return self.__hour

# # to recommend
class Clock(object):
    def __init__(self):
        self.__hour = 1
    def __setHour(self, hour):
        if 25& gt; hour & gt;0: self.__hour = hour
        else: raise BadHourException
    def __getHour(self):
        return self.__hour
    hour = property(__getHour, __setHour)
Copy the code

17. Use with to handle file opening

# # is not recommended
f = open("some_file.txt")
try:
    data = f.read()
    # Other file operations..
finally:
    f.close()

# # to recommend
with open("some_file.txt") as f:
    data = f.read()
    # Other file operations...
Copy the code

18. Ignore exceptions with with (Python 3 only)

# # is not recommended
try:
    os.remove("somefile.txt")
except OSError:
    pass

# # to recommend
from contextlib import ignored  # Python 3 only

with ignored(OSError):
    os.remove("somefile.txt")
Copy the code

19. Use with to handle locking

# # is not recommended
import threading
lock = threading.Lock()

lock.acquire()
try:
    # mutex...
finally:
    lock.release()

# # to recommend
import threading
lock = threading.Lock()

with lock:
    # mutex...
Copy the code

Follow the public account: “Python column”, the background reply “Tencent Architecture Resources 1”, get the big data learning resources package compiled by Tencent architects!!