Martin(Uncle Bob) once quipped in His book Clean Code: When your Code is being reviewed, the reviewer will yell angrily:

“What the fuck is this shit?” “Dude, What the fuck!”

It’s Bad Code if the censor just throws out a few words

“What the fuck?” .

That means you wrote Good Code. The only measure of code quality is the number of “WTF” words uttered per minute.

An elegant, clean, uncluttered piece of code usually comes with documentation and comments, and reading code is reading the author’s mind. Python development rarely applies design patterns as a development principle to the system as Java does. After all, design patterns are just a means of implementation, and code clarity is the ultimate goal, while Python is flexible and elegant. This is one of the reasons why Python is so popular with geeks.

Last week, I wrote an article: Code is more elegant, friends have expressed hope to write more, today I will continue this topic to write those Pythonic ways in Python, hope to introduce a piece of stone.

1. Chain comparison operation

age = 18
if age > 18 and x < 60:
    print("yong man")Copy the code

pythonic

if 18 < age < 60:
    print("yong man")Copy the code

Now that you understand the chain comparison operation, you should know why the following line of code outputs False.

>>> False= =False= =True 
FalseCopy the code

2, if/else ternary operation

if gender == 'male':
    text = 'male'
else:
    text = 'woman'Copy the code

pythonic

text = 'male' if gender == 'male' else 'woman'Copy the code

All C – like languages support ternary b? X :y, The Zen of Python has this sentence:

“There should be one– and preferably only one– obvious way to do it.”

When you can express logic clearly with if/else, there is no need to create an additional way to do it.

3. Truth value judgment

It is unnecessary and unprofessional to explicitly compare an object to True and False when checking whether it is True

if attr == True: do_something() if len(values) ! Do_something () = 0:Copy the code

pythonic

if attr:
    do_something()

if values:
    do_something()Copy the code

Comparison table of true and false values:

type False True
Boolean False (equivalent to 0) True (equivalent to 1)
string “” (empty string) Non-empty strings such as “”, “blog”
The numerical 0, 0.0 Non-zero values, such as 1, 0.1, -1, 2
The container [], (), {}, set() A container object with at least one element, for example: [0], (None,), [“]
None None The object of None

For /else statement

For else is a syntactic format that is unique to Python. Code in else is executed after the for loop has iterated through all elements.

flagfound = False
for i in mylist:
    if i == theflag:
        flagfound = True
        break
    process(i)

if not flagfound:
    raise ValueError("List argument missing terminal flag.")Copy the code

pythonic

for i in mylist:
    if i == theflag:
        break
    process(i)
else:
    raise ValueError("List argument missing terminal flag.")Copy the code

5. String formatting

s1 = "foofish.net"
s2 = "vttalk"
s3 = "welcome to %s and following %s" % (s1, s2)Copy the code

pythonic

s3 = "welcome to {blog} and following {wechat}".format(blog="foofish.net", wechat="vttalk")Copy the code

It’s hard to say that format takes less code than %s, but format is easier to understand.

“Explicit is Better than implicit — Zen of Python”

6. List slices

The first thing that comes to mind when getting partial elements in a list is to use a for loop to extract elements based on conditions, which is common in other languages, but Python also has powerful slicing capabilities.

items = range(10)

# odd
odd_items = []
for i in items:
    if i % 2! =0:
        odd_items.append(i)

# copy
copy_items = []
for i in items:
    copy_items.append(i)Copy the code

pythonic


# range of elements 1 through 4
sub_items = items[1:4]
# odd
odd_items = items[1: :2]
# copyCopy_items = items[::] or items[:]Copy the code

The subscripts of list elements can be expressed as both positive and negative numbers, with the last element in position -1 descending from right to left.

--------------------------
 | P | y | t | h | o | n |
--------------------------
   0   1   2   3   4   5 
  - 6  - 5  4 -  - 3  2 -  - 1
--------------------------Copy the code

7. Use generators

def fib(n):
    a, b = 0.1
    result = []
     while b < n:
        result.append(b)
        a, b = b, a+b
    return resultCopy the code

pythonic

def fib(n):
    a, b = 0.1
    while a < n:
        yield a
        a, b = b, a + bCopy the code

Above is a generator to generate the Fibonacci sequence. The nice thing about generators is that instead of loading all the elements into memory at once, they are returned only when iteratively fetched, whereas lists load all the elements into memory at once beforehand. In addition, the yield code is much clearer.

8. Get the dictionary element

d = {'name': 'foo'}
if d.has_key('name'):
    print(d['name'])
else:
    print('unkonw')Copy the code

pythonic

d.get("name"."unknow")Copy the code

9. Set dictionary defaults

When grouping by key, you have to check each time if the key already exists in the dictionary.

data = [('foo'.10), ('bar'.20), ('foo'.39), ('bar'.49)]
groups = {}
for (key, value) in data:
    if key in groups:
        groups[key].append(value)
    else:
        groups[key] = [value]Copy the code

pythonic

# First way
groups = {}
for (key, value) in data:
    groups.setdefault(key, []).append(value) 

# Second way
from collections import defaultdict
groups = defaultdict(list)
for (key, value) in data:
    groups[key].append(value)Copy the code

10. Dictionary derivation

Before python2.7, dictionary objects were built in a very unreadable manner

numbers = [1.2.3]
my_dict = dict([(number,number*2) for number in numbers])
print(my_dict)  # {1: 2, 2: 4, 3: 6}Copy the code

pythonic

numbers = [1, 2, 3] my_dict = {number: number * 2 for number in numbers} print(my_dict) # {1: 2, 2: 4, 3: My_dict = {number: number * 2 for number in numbers if number > 1} print(my_dict) # {2: 4, 3: 6}Copy the code

Dictionary derivations are a new feature in python2.7 that makes them much more readable, as are list and set derivations.

Python Zen (id:VTtalk)…

Zen Python