A few tips to make your Python code more Python

When we first started learning python, we understood the coding style requirements of Python. We can see its specific description by entering import this through Python terminal.

 

This is the famous "python Zen". In short, it is to write python compliant code, which is concise, elegant and readable.

Here are some common Python specifications and code styles that you can refer to and learn.

name

First, let's look at the variable naming convention (pep8):

Folder: package name. It is recommended to use only lowercase letters for naming, and underline is not recommended.

Module: lower case or underlined connection, such as module py , db_convert.py et al.

Class: hump type, initial capitalization, word direct connection.

class ThisIsAClass(object):
    pass

Functions: lowercase, separated by underscores

def this_is_a_func():
    pass

Variables: lowercase, separated by underscores

this_is_a_variable = 1

**Constant: * * all letters of the constant name are capitalized, and each word is connected by an underscore, such as THIS_IS_A_CONSTANT = 1

Grammatical style

1. Exchange values of a and b

Methods in other languages:

a = 5
b = 6
temp = a
a = b
b = temp

In python, a more concise method:

a = 5
b = 6
a, b = b, a
print(a, b)
Output: 6 5

2. Assignment of multiple variables

python can assign values to multiple variables in one line of code at the same time

a,b,c = 2,5,12

3. Merge strings

In the traditional string merging method, because the string object cannot be changed, each modification will produce a new object, which will consume a lot of memory.

list_str = ["hello ", "python", "!"]
result = ""
for i in list_str:
    result+=i
print(result)

In python, it is more efficient to use the join() method. Note that the join() method is only applicable to lists, tuples, collections and other types whose elements are strings.

list_str = ["hello ", "python", "!"]
result = "".join(list_str)
print(result)

Output: hello python!

4. List de duplication

Use the uniqueness of the set to de duplicate the list

a = [1, 2, 3, 1, 2,3 , 1, 3, 2, 4, 1, 3, 4, 5, 6, 5, 4, 4, 3, 6]
lst = list(set(a))
print(lst)
Output:

5.if/else ternary operation

Supported ternary operation formats in python:

Result when true if Judgment conditions else Result when false (note that there is no colon)
a=4
st = "a Greater than 4" if a>4 else "a Up to 4"
print(st)
Output: a Up to 4

6.enumerate

enumerate() is Python's built-in function. An iteratable object (list, string, etc.) can be formed into an index sequence, and the index and value can be obtained at the same time.

Get list elements and indexes

# General writing
names = ['Bob', 'Alice', 'Guido']
n = len(names)
for i in range(n):
    print(f'{i} {names[i]}')

# Use the enumerate() function
names = ['Bob', 'Alice', 'Guido']
for index, value in enumerate(names):
    print(f'{index}: {value}')
Output:
0: Bob
1: Alice
2: Guido

7. Unpacking

Unpacking is called unpacking in English, which is to take out the elements in the container one by one.

Extract the elements of the list / tuple and assign them to different variables

a, b, c = [1,2,3]
print(a, b, c)
Output: 1 2 3

Unpacking operation in function

In function calls, * can unpack tuples or lists into different parameters.

def func(a, b, c, d):
    print(a, b, c, d)

args = [1, 2, 3, 4]
func(*args)
Output: 1 2 3 4

In the function call, * * unpacks a dictionary in the form of key / value to make it an independent keyword parameter.

def func(a, b, c, d):
    print(a, b, c, d)

kwargs = {"a": 1, "b": 2, "c": 3, "d": 4}
func(**kwargs)
Output: 1 2 3 4

8. List derivation

List derivation can quickly generate a list that meets the specified requirements by using data types such as range interval, tuple, list, dictionary and set.

[expression for iteration variable in iteratable object [if conditional expression]]

[if conditional expression] can be omitted.

Generate a list whose elements are [1x1,2x2,3x3... nxn], assuming n = 10

# General method
lst = []
for i in range(1, 11):
    lst.append(i*i)
print(lst)
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]
# List derivation
lst = [i*i for i in range(1,11)]
print(lst)
Output:[1, 4, 9, 16, 25, 36, 49, 64, 81, 100]

There are no even items in the requested sequence

lst = [i*i for i in range(1, 11) if i % 2 != 0]
print(lst)
Output:[1, 9, 25, 49, 81]

9. Use the keyword in

  • In: returns True if a value is found in the specified sequence, otherwise False.

  • not in: returns True if no value is found in the specified sequence, otherwise False.

Determine whether the element is in the list

number=[1,2,3,4,5]
if 1 in number:
    print("1 in number")
if 0 not in number:
    print("0 not in number")

In the for loop, get each item of list, tuple and Dictionary:

list = [2, 3, 4]
for num in list:
    print (num)
    
dic = {"name": "xiaoming", "age": 18}
for k, v in dic.items():
    print(k, v)

10. Use zip to synchronize multiple lists

The zip() function is a Python built-in function. It can recombine the elements at the corresponding positions in multiple sequences (lists, tuples, dictionaries, collections, strings, etc.) to generate new tuples.

z = zip([1,2,3],[3,4,5])
print(list(z))
Output:[(1, 3), (2, 4), (3, 5)]

11. True value judgment

When judging whether a variable is True or not, Python has its own unique way. It does not need to write judgment conditions. It only needs to write the object directly after the if or while keyword.

Common cases where the true value is False:

  • Constants: None and False

  • Value: 0, 0.0, 0j

  • Sequence or set is empty: '', (), [], {}, set(), range(0)

    # This is recommended for Boolean objects
    x = True
    if x:
        pass
    # This is not recommended
    if x == True:
        pass
    
    lst = []
    # This is recommended for list objects
    if lst:
        pass
    # This is not recommended
    if len(lst) != 0:
        pass

    For more information on how to write python, you can refer to the book effctive python and the code specification requirements on the python official website

Keywords: Python Back-end

Added by mjgdunne on Wed, 12 Jan 2022 07:56:25 +0200