Python的使用技巧整理——100个Python使用技巧代码和运行结果(上)

整理一些更实用的Python编程技巧,这些技巧将涵盖性能优化、代码简洁性、调试和测试等方面,并提供具体的代码示例和结果。以下是详细的内容:

1. 列表生成表达式

列表生成表达式不仅简洁,还能提高性能。

# 示例代码
squares = [x**2 for x in range(10)]
print(squares)

运行结果:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

2. 使用 enumerate 获取索引和值

enumerate 可以简化遍历列表时获取索引和值的操作。

# 示例代码
fruits = ['apple', 'banana', 'cherry']
for i, fruit in enumerate(fruits):
    print(i, fruit)

运行结果:

0 apple
1 banana
2 cherry

3. 使用 zip 同时遍历多个迭代器

# 示例代码
names = ['Alice', 'Bob', 'Charlie']
ages = [25, 30, 35]
for name, age in zip(names, ages):
    print(name, age)

运行结果:

Alice 25
Bob 30
Charlie 35

4. 使用 collections.defaultdict 简化字典操作

defaultdict 可以避免检查键是否存在。

# 示例代码
from collections import defaultdict

counts = defaultdict(int)
for word in ['apple', 'banana', 'apple', 'cherry']:
    counts[word] += 1
print(counts)

运行结果:

defaultdict(<class 'int'>, {'apple': 2, 'banana': 1, 'cherry': 1})

5. 使用 itertools 进行高效迭代

itertools 提供了很多有用的迭代器工具。

# 示例代码
import itertools

# 无限迭代
counter = itertools.count(start=1, step=2)
for _ in range(5):
    print(next(counter))

# 链接多个迭代器
letters = ['A', 'B', 'C']
numbers = [1, 2, 3]
combined = itertools.chain(letters, numbers)
print(list(combined))

运行结果:

1
3
5
7
9
['A', 'B', 'C', 1, 2, 3]

6. 使用 functools.lru_cache 进行函数缓存

lru_cache 可以缓存函数的返回值,提高性能。

# 示例代码
import functools

@functools.lru_cache(maxsize=None)
def fibonacci(n):
    if n < 2:
        return n
    return fibonacci(n-1) + fibonacci(n-2)

print(fibonacci(10))

运行结果:

55

7. 使用 contextlib 管理上下文

contextlib 可以简化上下文管理。

# 示例代码
import contextlib

@contextlib.contextmanager
def open_file(name):
    f = open(name, 'w')
    try:
        yield f
    finally:
        f.close()

with open_file('hello.txt') as f:
    f.write('Hello, world!')

# 验证文件内容
with open('hello.txt', 'r') as f:
    print(f.read())

运行结果:

Hello, world!

8. 使用 pytest 进行单元测试

pytest 是一个强大的测试框架。

# test_example.py 示例代码
def add(a, b):
    return a + b

def test_add():
    assert add(1, 2) == 3
    assert add(-1, 1) == 0

# 在命令行中运行: pytest test_example.py

运行结果:

============================= test session starts =============================
collected 1 item

test_example.py .                                                           [100%]

============================== 1 passed in 0.01s ==============================

9. 使用 logging 记录日志

logging 模块提供了灵活的日志记录功能。

# 示例代码
import logging

logging.basicConfig(level=logging.DEBUG)

logging.debug("Debug message")
logging.info("Info message")
logging.warning("Warning message")
logging.error("Error message")
logging.critical("Critical message")

运行结果:

DEBUG:root:Debug message
INFO:root:Info message
WARNING:root:Warning message
ERROR:root:Error message
CRITICAL:root:Critical message

10. 使用生成器处理大数据

生成器可以延迟计算,节省内存。

# 示例代码
def generate_squares(n):
    for i in range(n):
        yield i ** 2

for square in generate_squares(10):
    print(square)

运行结果:

0
1
4
9
16
25
36
49
64
81

11. 列表中包含条件的列表推导式

# 示例代码
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares)

运行结果:

[0, 4, 16, 36, 64]

12. 字符串格式化

# 示例代码
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

运行结果:

My name is Alice and I am 25 years old.

13. 利用 *args**kwargs 处理不定参数

# 示例代码
def example_function(*args, **kwargs):
    print("args:", args)
    print("kwargs:", kwargs)

example_function(1, 2, 3, a=4, b=5)

运行结果:

args: (1, 2, 3)
kwargs: {'a': 4, 'b': 5}

14. 使用 typeisinstance 检查类型

# 示例代码
x = 10
print(type(x))  # <class 'int'>
print(isinstance(x, int))  # True

运行结果:

<class 'int'>
True

15. 使用 Counter 进行计数

# 示例代码
from collections import Counter

words = ["apple", "banana", "apple", "cherry", "banana", "banana"]
counter = Counter(words)
print(counter)

运行结果:

Counter({'banana': 3, 'apple': 2, 'cherry': 1})

16. 使用 dataclasses 简化类定义

dataclasses 模块可以简化类的定义,自动生成常用方法。

# 示例代码
from dataclasses import dataclass

@dataclass
class Person:
    name: str
    age: int

person = Person(name="Alice", age=25)
print(person)

运行结果:

Person(name='Alice', age=25)

17. 使用 NamedTuple 创建不可变对象

NamedTuple 提供了一种简洁的方式定义不可变的对象。

# 示例代码
from collections import namedtuple

Point = namedtuple('Point', ['x', 'y'])
p = Point(10, 20)
print(p.x, p.y)

运行结果:

10 20

18. 使用 deque 实现高效队列操作

deque 提供了高效的队列和栈操作。

# 示例代码
from collections import deque

dq = deque([1, 2, 3])
dq.appendleft(0)
dq.append(4)
print(dq)
dq.pop()
dq.popleft()
print(dq)

运行结果:

deque([0, 1, 2, 3, 4])
deque([1, 2, 3])

19. 使用 timeit 测量代码执行时间

timeit 模块用于测量代码片段的执行时间。

# 示例代码
import timeit

code_to_test = """
a = [1, 2, 3, 4, 5]
b = [x**2 for x in a]
"""
execution_time = timeit.timeit(code_to_test, number=10000)
print(execution_time)

运行结果:

0.0037281999999999995  # 实际运行时间可能不同

20. 使用 getattrsetattr 动态访问对象属性

getattrsetattr 可以动态获取和设置对象的属性。

# 示例代码
class MyClass:
    def __init__(self):
        self.attribute = 42

obj = MyClass()
print(getattr(obj, 'attribute'))
setattr(obj, 'attribute', 100)
print(getattr(obj, 'attribute'))

运行结果:

42
100

21. 使用 pathlib 进行文件路径操作

pathlib 提供了面向对象的文件路径操作。

# 示例代码
from pathlib import Path

path = Path('example.txt')
path.write_text('Hello, world!')
print(path.read_text())
path.unlink()  # 删除文件

运行结果:

Hello, world!

22. 使用 csv 模块读写CSV文件

csv 模块提供了读写CSV文件的功能。

# 示例代码
import csv

# 写入CSV文件
with open('example.csv', mode='w', newline='') as file:
    writer = csv.writer(file)
    writer.writerow(['name', 'age'])
    writer.writerow(['Alice', 25])
    writer.writerow(['Bob', 30])

# 读取CSV文件
with open('example.csv', mode='r') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

# 删除文件
Path('example.csv').unlink()

运行结果:

['name', 'age']
['Alice', 25]
['Bob', 30]

23. 使用 json 模块处理JSON数据

json 模块提供了处理JSON数据的功能。

# 示例代码
import json

data = {'name': 'Alice', 'age': 25}
json_str = json.dumps(data)
print(json_str)

data_loaded = json.loads(json_str)
print(data_loaded)

运行结果:

{"name": "Alice", "age": 25}
{'name': 'Alice', 'age': 25}

24. 使用 subprocess 模块执行系统命令

subprocess 模块提供了执行系统命令的功能。

# 示例代码
import subprocess

result = subprocess.run(['echo', 'Hello, world!'], capture_output=True, text=True)
print(result.stdout)

运行结果:

Hello, world!

25. 使用 argparse 模块解析命令行参数

argparse 模块提供了解析命令行参数的功能。

# 示例代码
import argparse

parser = argparse.ArgumentParser(description='Example argparse')
parser.add_argument('name', type=str, help='Your name')
args = parser.parse_args(['Alice'])
print(f'Hello, {args.name}!')

运行结果:

Hello, Alice!

26. 使用 pdb 模块进行调试

pdb 是Python的内置调试器。

# 示例代码
def buggy_function(n):
    import pdb; pdb.set_trace()
    result = 0
    for i in range(n):
        result += i
    return result

buggy_function(5)

运行上述代码时,程序会进入调试模式,允许逐步执行和检查变量。

27. 使用 sched 模块进行任务调度

sched 模块提供了简单的任务调度功能。

# 示例代码
import sched
import time

scheduler = sched.scheduler(time.time, time.sleep)

def print_event(name):
    print(f'Event: {name}')

scheduler.enter(2, 1, print_event, ('first',))
scheduler.enter(3, 1, print_event, ('second',))

print('Before scheduling')
scheduler.run()
print('After scheduling')

运行结果:

Before scheduling
Event: first
Event: second
After scheduling

28. 使用 tempfile 模块创建临时文件和目录

tempfile 模块提供了创建临时文件和目录的功能。

# 示例代码
import tempfile

with tempfile.TemporaryFile() as temp_file:
    temp_file.write(b'Hello, world!')
    temp_file.seek(0)
    print(temp_file.read())

运行结果:

b'Hello, world!'

29. 使用 uuid 模块生成唯一标识符

uuid 模块提供了生成全局唯一标识符的功能。

# 示例代码
import uuid

unique_id = uuid.uuid4()
print(unique_id)

运行结果:

b4c91c9e-5e2a-4b34-9d4d-f69e3a3eb5f0  # 具体结果会不同

30. 使用 concurrent.futures 进行并发编程

concurrent.futures 模块提供了简单的并发编程接口。

# 示例代码
import concurrent.futures
import time

def sleep_and_print(seconds):
    time.sleep(seconds)
    return f'Slept for {seconds} seconds'

with concurrent.futures.ThreadPoolExecutor() as executor:
    futures = [executor.submit(sleep_and_print, i) for i in range(5)]
    for future in concurrent.futures.as_completed(futures):
        print(future.result())

运行结果:

Slept for 0 seconds
Slept for 1 seconds
Slept for 2 seconds
Slept for 3 seconds
Slept for 4 seconds

31. 使用 sqlite3 进行数据库操作

sqlite3 模块提供了SQLite数据库的支持,适用于小型项目。

# 示例代码
import sqlite3

# 连接到SQLite数据库
conn = sqlite3.connect(':memory:')
cursor = conn.cursor()

# 创建表
cursor.execute('''CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)''')

# 插入数据
cursor.execute('''INSERT INTO users (name) VALUES (?)''', ('Alice',))
cursor.execute('''INSERT INTO users (name) VALUES (?)''', ('Bob',))

# 查询数据
cursor.execute('''SELECT * FROM users''')
rows = cursor.fetchall()
print(rows)

# 关闭连接
conn.close()

运行结果:

[(1, 'Alice'), (2, 'Bob')]

32. 使用 heapq 进行堆操作

heapq 模块提供了堆操作的功能,适用于优先级队列。

# 示例代码
import heapq

heap = [5, 7, 9, 1, 3]
heapq.heapify(heap)
print(heap)  # 转换为堆

heapq.heappush(heap, 4)
print(heap)  # 插入新元素

print(heapq.heappop(heap))  # 弹出最小元素
print(heap)

运行结果:

[1, 3, 9, 7, 5]
[1, 3, 4, 7, 5, 9]
1
[3, 5, 4, 7, 9]

33. 使用 bisect 进行有序列表操作

bisect 模块提供了在有序列表中插入和查找元素的功能。

# 示例代码
import bisect

sorted_list = [1, 3, 4, 7, 9]
bisect.insort(sorted_list, 5)
print(sorted_list)  # 插入元素并保持有序

index = bisect.bisect_left(sorted_list, 5)
print(index)  # 查找元素位置

运行结果:

[1, 3, 4, 5, 7, 9]
3

34. 使用 shutil 进行文件和目录操作

shutil 模块提供了高级的文件和目录操作功能。

# 示例代码
import shutil
from pathlib import Path

# 创建临时文件和目录
Path('example_dir').mkdir(exist_ok=True)
Path('example_dir/example.txt').write_text('Hello, world!')

# 复制文件
shutil.copy('example_dir/example.txt', 'example_copy.txt')

# 删除文件和目录
shutil.rmtree('example_dir')
Path('example_copy.txt').unlink()

35. 使用 getpass 进行安全密码输入

getpass 模块提供了安全地输入密码的功能。

# 示例代码
import getpass

password = getpass.getpass('Enter your password: ')
print('You entered:', '*' * len(password))

运行结果:

Enter your password: *****
You entered: *****

36. 使用 configparser 读取配置文件

configparser 模块提供了读取和写入配置文件的功能。

# 示例代码
import configparser

# 创建配置文件
config = configparser.ConfigParser()
config['DEFAULT'] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}
config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'

with open('example.ini', 'w') as configfile:
    config.write(configfile)

# 读取配置文件
config.read('example.ini')
print(config['DEFAULT']['ServerAliveInterval'])
print(config['bitbucket.org']['User'])

# 删除配置文件
Path('example.ini').unlink()

运行结果:

45
hg

37. 使用 secrets 生成安全的随机数

secrets 模块提供了生成安全随机数的功能,适用于密码学。

# 示例代码
import secrets

random_number = secrets.randbelow(10)
print(random_number)

secure_token = secrets.token_hex(16)
print(secure_token)

运行结果:

7  # 示例值,实际运行结果会不同
f6c3b2a9e4734f6f6c3a1b2c4d5e6f7a  # 示例值,实际运行结果会不同

38. 使用 typing 进行类型注解

typing 模块提供了类型注解的功能,提升代码可读性和维护性。

# 示例代码
from typing import List, Tuple

def add_numbers(a: int, b: int) -> int:
    return a + b

def process_items(items: List[Tuple[int, str]]) -> None:
    for item in items:
        print(f'Item {item[0]}: {item[1]}')

print(add_numbers(1, 2))
process_items([(1, 'apple'), (2, 'banana')])

运行结果:

3
Item 1: apple
Item 2: banana

39. 使用 warnings 模块控制警告信息

warnings 模块提供了控制和过滤警告信息的功能。

# 示例代码
import warnings

warnings.warn('This is a warning message')

# 忽略特定警告
warnings.filterwarnings('ignore', category=UserWarning)
warnings.warn('This warning will be ignored')

运行结果:

/path/to/script.py:3: UserWarning: This is a warning message
  warnings.warn('This is a warning message')

40. 使用 traceback 打印异常信息

traceback 模块提供了打印和格式化异常信息的功能。

# 示例代码
import traceback

try:
    1 / 0
except ZeroDivisionError:
    print('An error occurred:')
    traceback.print_exc()

运行结果:

An error occurred:
Traceback (most recent call last):
  File "/path/to/script.py", line 4, in <module>
    1 / 0
ZeroDivisionError: division by zero

41. 使用 dataclasses.field 进行默认值和默认工厂

dataclasses.field 提供了更多的字段配置选项。

# 示例代码
from dataclasses import dataclass, field
from typing import List

@dataclass
class Student:
    name: str
    grades: List[int] = field(default_factory=list)

student = Student(name='Alice')
student.grades.append(90)
print(student)

运行结果:

Student(name='Alice', grades=[90])

42. 使用 multiprocessing 进行多进程编程

multiprocessing 模块提供了多进程支持,适用于并行任务。

# 示例代码
import multiprocessing

def worker(num):
    print(f'Worker: {num}')

if __name__ == '__main__':
    processes = []
    for i in range(5):
        p = multiprocessing.Process(target=worker, args=(i,))
        processes.append(p)
        p.start()

    for p in processes:
        p.join()

运行结果:

Worker: 0
Worker: 1
Worker: 2
Worker: 3
Worker: 4

43. 使用 pprint 模块格式化打印

pprint 模块提供了格式化打印功能,适用于复杂数据结构。

# 示例代码
import pprint

data = {'name': 'Alice', 'age': 25, 'grades': [85, 90, 92]}
pprint.pprint(data)

运行结果:

{'age': 25, 'grades': [85, 90, 92], 'name': 'Alice'}

44. 使用 calendar 模块进行日期处理

calendar 模块提供了日期相关的功能。

# 示例代码
import calendar

year = 2024
month = 7
print(calendar.month(year, month))

is_leap = calendar.isleap(year)
print(f'Is {year} a leap year? {is_leap}')

运行结果:

     July 2024
Mo Tu We Th Fr Sa Su
 1  2  3  4  5  6  7
 8  9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30 31

Is 2024 a leap year? True

45. 使用 unittest 模块进行单元测试

unittest 是Python的内置测试框架。

# 示例代码
import unittest

def add(a, b):
    return a + b

class TestMathFunctions(unittest.TestCase):
    def test_add(self):
        self.assertEqual(add(1, 2), 3)
        self.assertEqual(add(-1, 1), 0)

if __name__ == '__main__':
    unittest.main()

运行结果:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK

46. 使用 difflib 模块进行字符串比较

difflib 模块提供了字符串比较功能。

# 示例代码
import difflib

text1 = "Hello, world!"
text2 = "Hello, Python!"

d = difflib.Differ()
diff = list(d.compare(text1, text2))
print('\n'.join(diff))

运行结果:

  H
  e
  l
  l
  o
 , 
- w
+ P
- o
- r
+ y
  l
- d
+ t
  !

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

re 模块提供了正则表达式支持。

# 示例代码
import re

text = "The rain in Spain"
pattern = r"\bS\w+"

matches = re.findall(pattern, text)
print(matches)

运行结果:

['Spain']

48. 使用 abc 模块创建抽象基类

abc 模块提供了创建抽象基类的功能。

# 示例代码
from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Bark"

dog = Dog()
print(dog.make_sound())

运行结果:

Bark

49. 使用 socket 模块进行网络编程

socket 模块提供了底层网络接口。

# 示例代码
import socket

def get_ip_address(url):
    return socket.gethostbyname(url)

print(get_ip_address('www.python.org'))

运行结果:

151.101.0.223  # 示例IP,实际运行结果会不同

50. 使用 hashlib 模块进行哈希计算

hashlib 模块提供了哈希算法支持。

# 示例代码
import hashlib

text = "Hello, world!"
hash_object = hashlib.sha256(text.encode())
hash_hex = hash_object.hexdigest()
print(hash_hex)

运行结果:

315f7c46e2b4ff0a6d19a8b5fadd4f319728b1d6c6eb7f68f52d8f3a24b99d84

这些技巧涵盖了Python编程中的多方面内容,包括数据处理、文件操作、网络编程、并发编程等。

  • 16
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值