Learn this to make your code more python

Python is a very flexible language. Many grammars are not available in other languages. Especially for people who change from C, Java and other languages to python, it is easy to write Python according to the writing methods of C, Java and other languages. For beginners, if they do not understand the python language thoroughly, they will write redundant code.

This article mainly introduces several simple skills to make you write Python code more python.

Variable exchange

  • Python writing
a, b = b, a
  • Common writing
tmp = a;
a = b;
b = tmp;

Loop through interval elements

# Generators and lists save more memory
# range(start, end, step)
# [start, end) contains the beginning but not the end
for i in range(1, 1000, 2) # python3
for i in range(6) # python3
for i in xrange(6) #python2

In Python 2, there are range and xrange2 writing methods. Xrange is a generator writing method, which saves more memory. Range in Python 3 is equivalent to xrange in Python 2.

The generator can only be generated dynamically when it is used, and can only be used once. For example, range(1000000). In Python 2, a list of 1 million elements will be generated in memory, while in Python 3, a list will not be generated, but a generator, which occupies a small memory.

If you are still using Python 2, it is recommended to use xrange instead of range

  • Java writing
for(int i = start; i < end; i += step) {
    // ....
}
  • Generator extension
# Define a generator
odd = (num for num in range(10) if num % 2 == 1)
for num in odd:
    print(num)

# Define a generator
def fib(max):
    n, a, b = 0, 0, 1
    while n < max:
        yield b
        a, b = b, a + b
        n = n + 1

>>> type(fib(3)) 
<generator object fib at 0x10e610728>
>>> for num in fib(3):
...     print(num)
... 
1
1
2

def odd():
    print('step 1')
    yield 1
    print('step 2')
    yield 3
    print('step 3')
    yield 5

gen = odd()

print(next(gen))
print(next(gen))
print(next(gen))

Indexes

  • Python writing
num_list = [1, 4, 9]
for i, val in enumerate(num_list):
    print(i, '-->', val)
  • Common writing
num_list = [1, 4, 9]
for i in range(len(num_list))
    print(i, '-->', num_list[i])

Obviously, python writing is more intuitive and elegant.

String splicing

  • Python writing
names = ['Tom', 'Jack', 'Sam']
','.join(names) 
  • Common writing
names = 'Tom' + 'Jack' + 'Sam'

Each + operation will generate a new string, resulting in a waste of memory. However, in the whole process of join, only one string object will be generated

File opening and closing

  • Python writing
# Writing method 2
with open('a.txt') as f:
    data = f.read()
  • Common writing
f = open('a.txt')
try:
    data = f.read()
finally:
    f.close()

with, Python will automatically manage the opening and closing of file streams without manual operation.

List operation

  • Python writing
from collections import deque


names = deque(['c', 'd', 'e'])
names.popleft()
names.appendleft('b')
names.append('f')

# names => deque(['b', 'd', 'e', 'f'])
  • Common writing
names = list['c', 'd', 'e']
names.pop(0)
names.insert(0, 'b')
names.append('f')

List can also use pop(0) to delete the first element, but the list is stored sequentially in memory. Deleting the first element will cause all subsequent elements to move forward, which is very inefficient and similar to inserting.

If there are a lot of delete and insert operations at the beginning, avoid using list.

Destructuring assignment

  • Python writing
student = ['Tom', 18, 'male']
name, age, gender = student
print(name, age, gender)
# Tom 18 male

num_list = [100, 19, 20, 98]
first, *left_num_list, last = num_list
print(first, left_num_list, last)
# 100 [19, 20] 98

student = [['Tom', (98, 96, 100)], ['Jack', (98, 96, 100)]]

for name, (first, second, third) in student:
    print(name, first, second, third)

student = {
    'name': 'Tom',
    'age': 18
}

# python3
for k, v in student.items():
    print('k', '-->', v)

# python2
for k, v in student.iteritems():
    print('k', '-->', v)

The dictionary is similar. In Python 2, the items method of the dictionary will return a list. When the dictionary is large, it will consume a lot of memory. The iteritems method returns the generator.

In Python 3, there is no iteritems, and items is equivalent to the iteritems of Python 2.

If you are using Python 2, use iteritems instead of items

Derivation

  • Python writing
# Generate odd numbers from 1 to 100
odd = [i for i in range(1, 100) if i % 2 == 1]

# Set a and b to a number respectively, and find all combinations with a sum greater than 100
result = [(x, y) for x in a_set for y in b_set if x + y > 100]
  • Common writing
# Generate odd numbers from 1 to 100
result = []
for i in range(100):
    if i % 2 == 1:
        result.append(i)
        
# Set a and b to a number respectively, and find all combinations with a sum greater than 100
result = []
for x in a_set:
    for y in b_set:
        if x + y > 100:
        result.append((x, y))

That's all for this sharing ~ if it helps you, remember to pay attention before you go ~ thank you for reading.

Keywords: Python

Added by krraleigh on Thu, 30 Dec 2021 12:57:55 +0200