Python usage conventions are the syntax, semantics, and structures that are often used, so that they are written more in Python style and look more like a native Pythoner.

The purpose of this series is to sort through Python usage habits.

1. if not x

Use x and not x directly to determine whether x is None or null

x = [1.3.5]

if x:
    print('x is not empty ')

if not x:
    print('x is empty')
Copy the code

I’m not going to write Pythoner

if x and len(x) > 0:
    print('x is not empty ')

if x is None or len(x) == 0:
    print('x is empty')
Copy the code

2. Enumerate enumeration

Use enumerate to enumerate containers. The second parameter indicates the starting value of the index

x = [1.3.5]

for i, e in enumerate(x, 10) : # enumerationprint(i, e)
Copy the code

Pythoner is not enough:

i = 0

while i < len(x):
    print(i+10, x[i])
    i+=1
Copy the code

3. in

To determine if a string contains a substring, using in is significantly more readable:

x = 'zen_of_python'
if 'zen' in x:
    print('zen is in')
Copy the code

Find returns -1:

if x.find('zen') != - 1:
    print('zen is in')
Copy the code

4 zip package

Zip package combined with for output pair, more consistent with custom:

keys = ['a'.'b'.'c']
values = [1.3.5]

for k, v in zip(keys, values):
    print(k, v)
Copy the code

The following is not a Python convention:

d = {}
i = 0
for k in keys:
    print(k, values[i])
    i += 1
Copy the code

5 a pair of ‘ ‘ ‘

Print a string divided into multiple lines, using a pair of “” is more Python convention:

print(' ''"Oh no!" He exclaimed.
"It's the blemange!"" 'Copy the code

The following is too unPython:

print('"Oh no!" He exclaimed.\n' +
      'It\'s the blemange!" ')
      
Copy the code

6 Exchange Elements

Unpack assignment directly, more Python style:

a, b = 1.3A,b = b, a # swap a,bCopy the code

Do not use the temporary TMP variable. This is not Python:

tmp = a
a = b
b = tmp
Copy the code

7 the join series

Concatenated strings, more like join:

chars = ['P'.'y'.'t'.'h'.'o'.'n']
name = ' '.join(chars)
print(name)
Copy the code

The following is not a Python convention:

name = ' '
for c in chars:
    name += c
print(name)
Copy the code

8 List generation

List-generating builds are efficient and Python friendly:

data = [1.2.3.5.8]
result = [i * 2 for i in data if i & 1] # the odd number times2
print(result) # [2.6.10]
Copy the code

Pythoner is not enough:

results = []
for e in data:
    if e & 1:
        results.append(e*2)
print(results)
Copy the code

Dictionary generation

In addition to list generators, there are dictionary generators:

keys = ['a'.'b'.'c']
values = [1.3.5]

d = {k: v for k, v in zip(keys, values)}
print(d)
Copy the code

Not quite Pythoner:

d = {}
for k, v in zip(keys, values):
    d[k] = v
print(d)
Copy the code

10 __name__ == '__main__'There are much use

There was a time when someone else wrote code like this and we used it like this, but we didn’t really know exactly what it did.

def mymain():
    print('Doing something in module', __name__)


if __name__ == '__main__':
    print('Executed from command line')
    mymain()
Copy the code

Add the script above named MyModule and print it directly, regardless of whether it is launched directly in vscode or pycharm:

Executed from command line
Doing something in module __main__
Copy the code

This is not surprising, as we would expect, since this will be printed with or without the __main__ clause.

But when we import MyModule, if we don’t have this sentence, we just print:

In [2] :import MyModule
Executed from command line
Doing something in module MyModule
Copy the code

Simply executing mymain with an import is not what we expected.

If there is a main clause, import it as expected:

In [6] :import MyModule

In [7]: MyModule.mymain()
Doing something in module MyModule
Copy the code

That was the first installment of 10 Python idioms. Hope to help you, welcome to watch oh.

Machine learning online manual for Machine learning Deep Learning Notes album for AI Basics download (PDF update25Set) Machine learning basics of Mathematics album get a discount website knowledge planet coupon, copy the link directly open: HTTPS://t.zsxq.com/yFQV7am site QQ group 1003271085, join wechat group please scan code like articles, click a look
Copy the code