一些Python惯用法

Safe Hammad
Python Northwest

Make a script both importable and executable

if __name__ == '__main__':

Test for "truthy" and "falsy" values

if x:

if not x:

What is truth?

TrueFalse
Non-empty stringEmpty string
Number not 0Number 0
Non-empty container: len(x) > 0Empty container: len(x) == 0
-None
TrueFalse
__nonzero__ (2.x) / __bool__ (3.x)__nonzero__ (2.x) / __bool__ (3.x)

Use in where possible

#Contains:
if x in items:

#Iteration:
for x in items:

Swap values without temp variable

a, b = b, a

Build strings using sequence

''.join(some_strings)

EAFP is preferable to LBYL

"It's Easier to Ask for Forgiveness than Permission."

"Look Before You Leap"

try:

except:

Enumerate

for i, item in enumerate(items):

Build lists using list comprehensions

[i * 3 for i in data if i > 10]

Create dict from keys and values using zip

d = dict(zip(keys, values))

Default Dict

from collections import defaultdict

l = [('a', 1), ('b', 2), ('a', 3), ('c', 4)]
d = defaultdict(list)
for k,v in l:
    d[k].append(v)
l = [('a', 1), ('b', 2), ('a', 3), ('c', 4)]
d = {}
for k,v in l:
    d.setdefault(k,[]).append(v)

Retuen a default value if None

return x or 'default'