Python because of the simplicity of the language, let's write code in the way of human thinking, it's easier for the novice to start, and the old bird can't let go.
To write python (elegant, authentic and neat) code, and to observe the big bull code more often, there are many excellent source codes on Github that are worth reading, such as requests, flask and tornado. Here is my reference to other articles and my own experience to collect some common Python codes Writing, hope to help you develop the habit of writing good code.
01. Variable exchange
Bad
tmp = a a = b b = tmp
Pythonic
a,b = b,a
02. List derivation
Bad
my_list = [] for i in range(10): my_list.append(i*2)
Pythonic
my_list = [i*2 for i in range(10)]
03. Single line expression
Although list derivation is widely praised for its simplicity and expressiveness.
But there are many expressions that can be written as a single line, which is not a good practice.
Bad
What I don't know in the learning process python learning qun, 855408893 There are good learning video tutorials, development tools and e-books in the group. Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn print 'one'; print 'two' if x == 1: print 'one' if <complex comparison> and <other complex comparison>: # do something
Pythonic
print 'one' print 'two' if x == 1: print 'one' cond1 = <complex comparison> cond2 = <other complex comparison> if cond1 and cond2: # do something
04. Traversal with index
Bad
for i in range(len(my_list)): print(i, "-->", my_list[i])
Pythonic
for i,item in enumerate(my_list): print(i, "-->",item)
05. Sequence unpacking
Pythonic
a, *rest = [1, 2, 3] # a = 1, rest = [2, 3] a, *middle, c = [1, 2, 3, 4] # a = 1, middle = [2, 3], c = 4
06. String splicing
Bad
letters = ['s', 'p', 'a', 'm'] s="" for let in letters: s += let
Pythonic
letters = ['s', 'p', 'a', 'm'] word = ''.join(letters)
07. True or false judgment
Bad
if attr == True: print 'True!' if attr == None: print 'attr is None!'
Pythonic
if attr: print 'attr is truthy!' if not attr: print 'attr is falsey!' if attr is None: print 'attr is None!'
08. Accessing dictionary elements
Bad
d = {'hello': 'world'} if d.has_key('hello'): print d['hello'] # prints 'world' else: print 'default_value'
Pythonic
d = {'hello': 'world'} print d.get('hello', 'default_value') # prints 'world' print d.get('thingy', 'default_value') # prints 'default_value' # Or: if 'hello' in d: print d['hello']
09. Operation list
Bad
What I don't know in the learning process python learning qun, 855408893 There are good learning video tutorials, development tools and e-books in the group. Share with you the current talent needs of python enterprises and how to learn python from scratch, and what to learn a = [3, 4, 5] b = [] for i in a: if i > 4: b.append(i)
Pythonic
a = [3, 4, 5] b = [i for i in a if i > 4] # Or: b = filter(lambda x: x > 4, a)
Bad
a = [3, 4, 5] for i in range(len(a)): a[i] += 3
Pythonic
a = [3, 4, 5] a = [i + 3 for i in a] # Or: a = map(lambda i: i + 3, a)
10. File reading
Bad
f = open('file.txt') a = f.read() print a f.close()
Pythonic
with open('file.txt') as f: for line in f: print line
11. Code continuation
Bad
my_very_big_string = """For a long time I used to go to bed early. Sometimes, \ when I had put out my candle, my eyes would close so quickly that I had not even \ time to say "I'm going to sleep."""" from some.deep.module.inside.a.module import a_nice_function, another_nice_function, \ yet_another_nice_function
Pythonic
my_very_big_string = ( "For a long time I used to go to bed early. Sometimes, " "when I had put out my candle, my eyes would close so quickly " "that I had not even time to say "I'm going to sleep."" ) from some.deep.module.inside.a.module import ( a_nice_function, another_nice_function, yet_another_nice_function)
12. Explicit code
Bad
def make_complex(*args): x, y = args return dict(**locals())
Pythonic
def make_complex(x, y): return {'x': x, 'y': y}
13. Use placeholders
Pythonic
filename = 'foobar.txt' basename, _, ext = filename.rpartition('.')
14. Chain comparison
Bad
if age > 18 and age < 60: print("young man")
Pythonic
if 18 < age < 60: print("young man")
If you understand the chain comparison operation, you should know why the output of the following line of code is False
>>> False == False == True False
15. Binocular operation
This reservation. Use as you like.
Bad
if a > 2: b = 2 else: b = 1 #b = 2
Pythonic
a = 3 b = 2 if a > 2 else 1 #b = 2