A few tips to make your python code more pythonic

1. Multi-variable assignment

Assign values ​​to multiple variables at the same time

# 分别为 a, b, c 赋值 1, 2, 3
a, b, c = 1, 2, 3
print('a={}, b={}, c={}'.format(a, b, c))
# a=1, b=2, c=3

2. Variable value exchange

Swap variable values ​​without intermediate variables

# 交换 a, b 的值
a, b = 1, 2
a, b = b, a
print('a={}, b={}'.format(a, b))
# a=2, b=1

3. Multiple judgments

Use in instead of or to make judgments

# 判断 a 是否等于 1, 2, 3 中的某一个
a = 2
if a in (1, 2, 3):
    print(True)
else:
    print(False)
# True

4. Multi-list synchronization processing

Use zip to operate corresponding elements of multiple lists at the same time

# 两个列表中同索引元素相减成新列表
x, y, z = [10, 20], [1, 2], []
for i, j in zip(x, y):
    z.append(i - j)
print(z)
# [9, 18]

5. Remove duplicate elements from list

Use set to remove duplicate elements from a list

# 去除列表中重复出现的字符 a
x, y = ['a', 'b', 'c', 'a', 'd'], []
y = list(set(x))
print(x, y, sep='\n')
# ['a', 'b', 'c', 'a', 'd']
# ['b', 'a', 'c', 'd']

6. Context Management

For operations that require manual release of resources at the end, you can put them in the context manager to automatically release the resources.

# 将写操作放入上下文管理器中
with open('hello.txt', 'w') as f:
	f.write('Hello World!')
# Hello World!

7. Sequence iteration

Use the enumeration function enumerate to enumerate iterable objects and corresponding indexes

x = ['a', 'b', 'c', 'd', 'e']
for i, j in enumerate(x):
    print(i, j)
# 0 a
# 1 b
# 2 c
# 3 d
# 4 e

8. Get list contents

Remove elements from the list at once

# 对应取出列表中所有元素
x = [1, 2, 3, 4]
x0, x1, x2, x3 = x
print(x0, x1, x2, x3)
# 1 2 3 4

# 只取出列表首尾元素
x = [1, 2, 3, 4]
head, *_, tail = x
print(head, tail)
# 1 4

9. Convert string list to string

Use the join method to specify the interval to merge the string list into a long string

# 间隔空格将字符串列表连接成长字符串
x = ['Hello', 'World', '!']
y = ' '.join(x)
print(y)
# Hello World !

10. Ternary arithmetic

Use if···else··· to implement ternary arithmetic

# 如果 a 大于 10 赋值给 b 真,否则假
a = 10
b = True if a > 5 else False
print(b)
# True

11. Printout format

Print output with f string to improve code readability

# 打印名字和年龄
name = 'Xiao Ming'
age = 18
print('name: %s, age: %d' % (name, age))
print('name: {}, age: {}'.format(name, age))
print(f'name: {
      
      name}, age: {
      
      age}')
# name: Xiao Ming, age: 18
# name: Xiao Ming, age: 18
# name: Xiao Ming, age: 18

12. Chain comparison

Simplify AND logic in conditional judgment

# a 同时满足两个条件
a, b = 10, 0
if 5 < a < 15:
	b = - a
print(b)
# -10

13. String flipping

# 将字符串 x 进行翻转
x = 'olleH'
y = x[::-1]
print(y)
# Hello

14. Convert double list to dictionary format

Use dict and zip functions to convert list correspondence into dictionary format

# x 和 y 中对应元素变为字典键值对
x = ['name', 'age']
y = ['Xiao Ming', 18]
z = dict(zip(x, y))
print(z)
# {'name': 'Xiao Ming', 'age': 18}

15. Iterator generates array

Generate array using iterator

# 生成 20 以内偶数数组
x = [i*2 for i in range(10)]
print(x)
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

16. switch judgment form

Use the get method to implement the switch function

# 根据索引找到姓名并打印
index = 2
name = {
    
    
    0: "Xiao Ming",
    1: "Er Ming",
    2: "Da Ming"
    }.get(index, "Not Found")
print(f'index: {
      
      index}, name: {
      
      name}')
# ndex: 2, name: Da Ming

17. Two-dimensional array traversal

# 循环遍历二维数组并按行打印
x = [
    ['Xiao Ming', 18],
    ['Er Ming', 19],
    ['Da Ming', 20]
]
for name, age in x:
    print(f'name: {
      
      name}, age: {
      
      age}')
# name: Xiao Ming, age: 18
# name: Er Ming, age: 19
# name: Da Ming, age: 20

18. List cutting

# 切割列表元素,前两个,中间两个,后两个
x = [1, 2, 3, 4, 5, 6]
x1 = x[:2]
x2 = x[2:4]
x3 = x[-2:]
print(x1, x2, x3, sep='\n')
# [1, 2]
# [3, 4]
# [5, 6]

19. Determine whether the list is empty

# 直接将列表名作为判断条件
x = []
if x:
    print('x is not empty.')
else:
    print('x is empty.')
# x is empty.

Insert image description here

Guess you like

Origin blog.csdn.net/Wenyuanbo/article/details/119542818