返回

破釜沉舟,助你升级Python技能:摒弃18个坏习惯!

闲谈

1. ** 字符串拼接用+号

坏的做法:

name = "John"
age = 30
sentence = "My name is " + name + " and I am " + str(age) + " years old."

好的做法是使用f-strings:

name = "John"
age = 30
sentence = f"My name is {name} and I am {age} years old."

2. 使用==比较数字

坏的做法:

if 1 == 1:
    print("True")

好的做法是使用is比较数字:

if 1 is 1:
    print("True")

3. 使用len()来检查字符串是否为空

坏的做法:

if len(string) == 0:
    print("String is empty")

好的做法是使用string.isEmpty()来检查字符串是否为空:

if string.isEmpty():
    print("String is empty")

4. 使用in来检查元素是否在列表中

坏的做法:

if element in list:
    print("Element is in the list")

好的做法是使用list.contains()来检查元素是否在列表中:

if list.contains(element):
    print("Element is in the list")

5. 使用for循环来遍历列表

坏的做法:

for i in range(len(list)):
    print(list[i])

好的做法是使用for-in循环来遍历列表:

for element in list:
    print(element)

6. 使用while循环来遍历列表

坏的做法:

i = 0
while i < len(list):
    print(list[i])
    i += 1

好的做法是使用for-in循环来遍历列表:

for element in list:
    print(element)

7. 使用breakcontinue来控制循环

坏的做法:

for i in range(10):
    if i == 5:
        break
    print(i)
for i in range(10):
    if i == 5:
        continue
    print(i)

好的做法是使用for-else循环来控制循环:

for i in range(10):
    if i == 5:
        break
else:
    print("Loop completed")
for i in range(10):
    if i == 5:
        continue
else:
    print("Loop completed")

8. 使用if-else语句来检查条件

坏的做法:

if condition:
    # Do something
else:
    # Do something else

好的做法是使用if-elif-else语句来检查条件:

if condition1:
    # Do something
elif condition2:
    # Do something else
else:
    # Do something else

9. 使用try-except语句来处理异常

坏的做法:

try:
    # Do something
except:
    # Handle the exception

好的做法是使用try-except-finally语句来处理异常:

try:
    # Do something
except Exception as e:
    # Handle the exception
finally:
    # Do something regardless of whether an exception occurred

10. 使用print()函数来打印信息

坏的做法:

print("Hello, world!")

好的做法是使用logging模块来打印信息:

import logging

logging.info("Hello, world!")

11. 使用os模块来执行系统命令

坏的做法:

import os

os.system("ls -l")

好的做法是使用subprocess模块来执行系统命令:

import subprocess

subprocess.run(["ls", "-l"])

12. 使用time模块来测量代码的执行时间

坏的做法:

import time

start = time.time()
# Do something
end = time.time()
print(end - start)

好的做法是使用timeit模块来测量代码的执行时间:

import timeit

code = """
# Do something
"""

print(timeit.timeit(code, number=10000))

13. 使用random模块来生成随机数

坏的做法:

import random

print(random.randint(1, 10))

好的做法是使用numpy模块来生成随机数:

import numpy as np

print(np.random.randint(1, 10))

14. 使用math模块来进行数学运算

坏的做法:

import math

print(math.sin(math.pi / 2))

好的做法是使用numpy模块来进行数学运算:

import numpy as np

print(np.sin(np.pi / 2))

15. 使用re模块来进行正则表达式匹配

坏的做法:

import re

pattern = "Hello, world!"
string = "Hello, world!"

if re.match(pattern, string):
    print("Match found")

好的做法是使用regex模块来进行正则表达式匹配:

import regex

pattern = "Hello, world!"
string = "Hello, world!"

if regex.match(pattern, string):
    print("Match found")

16. 使用json模块来解析JSON数据

坏的做法:

import json

data = '{"name": "John", "age": 30}'
obj = json.loads(data)

print(obj["name"])
print(obj["age"])

好的做法是使用ujson模块来解析JSON数据:

import ujson

data = '{"name": "John", "age": 30}'
obj = ujson.loads(data)

print(obj["name"])
print(obj["age"])

17. 使用xml模块来解析XML数据

坏的做法:

import xml.etree.ElementTree as ET

tree = ET.parse("data.xml")
root = tree.getroot()

for child in root:
    print(child.tag, child.attrib)

好的做法是使用lxml模块来解析XML数据:

import lxml.etree as ET

tree = ET.parse("data.xml")
root = tree.getroot()

for child in root:
    print(child.tag, child.attrib)

18. 使用BeautifulSoup库来解析HTML数据

坏的做法:

from bs4 import BeautifulSoup

html = """
<html>
<head>

</head>
<body>
<h1>Hello, world!</h1>
</body>
</html>
"""

soup = BeautifulSoup(html, "html.parser")

print(soup.title.string)

好的做法是使用html5lib库来解析HTML数据:

from html5lib import HTMLParser

parser = HTMLParser()
tree = parser.parse(html)

print(tree.title.string)