Loading

《Python进阶》学习笔记

《Python进阶》学习笔记

部分原创,仅个人关于《Python进阶》的学习笔记

import warnings
# 忽略警告
warnings.filterwarnings("ignore")

*args的用法

def test_args(f_arg,*argv):
    print("第一个参数是:",f_arg)
    for arg in argv:
        print("其他argv参数是:",arg)
test_args('1','2','3')
第一个参数是: 1
其他argv参数是: 2
其他argv参数是: 3

**kwargs的用法

# 如果你想要在一个函数里处理带名字的参数,可以使用**kwargs
def greet_me(**kwargs):
    for key,value in kwargs.items():
        print("{0}:{1}".format(key,value))
greet_me(name="zhouwp")
name:zhouwp

使用*args和**kwargs调用函数

def test_args_kwargs(name,age,high):
    print("name:",name)
    print("age:",age)
    print("high:",high)
args = ("zwp",38,164)
test_args_kwargs(*args)
name: zwp
age: 38
high: 164
kwargs = {"name": "zhouwp","age":38,"high":164}
test_args_kwargs(**kwargs)
name: zhouwp
age: 38
high: 164

迭代器(Iterator)

任意对象,只要定义了next或者__next__方法,它就是一个迭代器。

生成器(Generators)

def generator_fun():
    for i in range(10):
        yield i
for item in generator_fun():
    print(item)
0
1
2
3
4
5
6
7
8
9
# 斐波那契数列
def fibon(n):
    a = b = 1
    for i in range(n):
        yield a
        a,b = b, a+b
for x in fibon(20):
    print(x)
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987
1597
2584
4181
6765

Python内置迭代函数iter

my_string = "hundsun"
my_iter = iter(my_string)
next(my_iter)
'h'
next(my_iter)
'u'
next(my_iter)
'n'
next(my_iter)
'd'
next(my_iter)
's'
next(my_iter)
'u'
next(my_iter)
'n'

Map

将一个函数映射到一个输入列表的所有元素上。

# 不用map的情况
items = [1,2,3,4,5]
squared = []
for i in items:
    squared.append(i**2)
squared
[1, 4, 9, 16, 25]
# 接下来,我们试试用map的情况
squared_map = list(map(lambda x:x**2,items))
squared_map
[1, 4, 9, 16, 25]

Filter

过滤列表中的元素,返回一个由所有符合要求的元素所构成的列表,符合要求即函数映射到该元素时返回值为True

基本用法

number_list = range(-5,5)
less_than_zero = filter(lambda x:x<0,number_list)
print(less_than_zero)
print(list(less_than_zero))
<filter object at 0x000001594D0CD630>
[-5, -4, -3, -2, -1]

使用自定义函数

定义一个函数,然后使用 filter() 来过滤元素。

def is_even(x):
    return x % 2 == 0
numbers = [1, 2, 3, 4, 5, 6]
even_numbers = filter(is_even, numbers)
print(list(even_numbers))
[2, 4, 6]

过滤多个序列

numbers = [1, 2, 3, 4]
letters = ['a', 'b', 'c', 'd']
pairs = filter(lambda x: x[0] % 2 == 0, zip(numbers, letters))
print(list(pairs))
[(2, 'b'), (4, 'd')]

使用 None 作为函数

如果函数参数为 None,则 filter() 会检查序列中的元素是否为真值。

numbers = [0, 1, 2, 3, 0, 5]
non_zero_numbers = filter(None, numbers)
print(list(non_zero_numbers))
[1, 2, 3, 5]

链式调用

可以链式使用 filter() 来应用多个过滤条件。

numbers = range(10)
filtered_numbers = filter(lambda x: x > 3, filter(lambda x: x % 2 == 0, numbers))
print(list(filtered_numbers))
[4, 6, 8]

Reduce

当要对一个列表进行计算并返回结果时,Reduce是一个非常有用的函数。

# 计算⼀个整数列表的乘积
from functools import reduce
product = reduce((lambda x,y:x*y),[1,2,3,4])
product
24

set数据结构

# set和list类似,区别在于set不能包含重复的值。

交集(intersection)

a = set([1,2,3,4,5,6])
b = set([3,5])
c = b.intersection(a)
c
{3, 5}

差集(difference)

# 相当于用一个集合的数据减去另一个集合的数据。
aa = set([1,2,3,4,5,6])
bb = set([3,5])
cc = a.difference(b)
cc
{1, 2, 4, 6}

三元运算符

# condition_is_true if condition else condition_is_false

实际业务编程中的应用案例

  • 在生成用户界面或报告时,根据条件来决定显示的文本或样式
status = "active" if user.is_active else "inactive"
print(f"User status: {status}")
  • 当需要一个变量的值,但这个值可能是 None 或者未定义时,可以设置一个默认值。
default_value = some_value if some_value is not None else "default"
  • 在需要根据条件执行不同操作时,三元运算符可以减少 if-else 语句的使用。
result = process_data(data) if data else "No data to process"
  • 条件赋值
temperature = "hot" if current_temp > 30 else "cold"
  • 根据用户的角色或权限来决定是否允许执行某个操作。
is_allowed = True if user.role in ["admin", "editor"] else False

装饰器

装饰器是一种设计模式,它允许用户在不修改函数内容的情况下增加函数的功能。装饰器本质上是一个函数,它接收一个函数作为参数并返回一个新的函数。

def decorator(func):
    def wrapper(*args, **kwargs):
        # 在函数执行前做一些操作
        result = func(*args, **kwargs)
        # 在函数执行后做一些操作
        return result
    return wrapper

应用场景:

  • 日志记录:在函数执行前后添加日志记录,方便调试和追踪。
  • 性能测试:测量函数执行时间。
  • 事务处理:确保数据库操作的原子性。
  • 权限校验:在执行函数前检查用户权限。
  • 缓存:缓存函数的结果,避免重复计算。
  • 限流:控制函数的调用频率,防止滥用。
  • 类型检查:确保函数参数符合预期类型。
  • 异常处理:统一处理函数可能抛出的异常。

逻辑:

装饰器的逻辑主要涉及三个部分:

  • 装饰器函数:这是一个接收函数作为参数的函数。
  • 包装函数(wrapper):这是装饰器返回的新函数,它将被用来包装原始函数。
  • 执行流程:
    • 首先执行装饰器函数中的逻辑(如果有)。
    • 然后调用原始函数,并传递必要的参数。
    • 最后执行装饰器函数中的其他逻辑(如果有),并返回结果。

示例:

# 装饰器函数,say_hello 就是 func
def my_decorator(func):
    # 内部定义的函数,用来包装 func 并添加额外的功能
    def wrapper(*args, **kwargs):
        print("Something is happening before the function is called.")
        # func 即被包装函数
        result = func(*args, **kwargs)  ###实际对应的是say_hello函数,执行say_hello函数中的逻辑
        print("Something is happening after the function is called.")
        return result
    return wrapper

@my_decorator
# say_hello函数是my_decorator装饰函数中func的
def say_hello():
    print("Hello,ZWP!")

say_hello()
Something is happening before the function is called.
Hello,ZWP!
Something is happening after the function is called.

总结:

在这个例子中,my_decorator 是一个装饰器,它被用来装饰 say_hello 函数。当调用 say_hello() 时,实际上调用的是 wrapper 函数,它在调用原始的 say_hello 函数前后分别打印了一些信息。

高级用法:

使用 functools.wraps 来保持被装饰函数的元数据,如函数名和文档字符串。

from functools import wraps

#装饰函数,其中参数func,say_hello 就是 func
def my_decorator(func):
    @wraps(func)
    def wrapper(*args, **kwargs):
        # 装饰逻辑
        return func(*args, **kwargs)
    return wrapper

@my_decorator
def greet(name):
    """Greet someone."""
    print(f"Hello, {name}!")

print(greet.__name__)
print(greet.__doc__)
greet
Greet someone.

装饰器的应用场景

授权

from flask import Flask, jsonify, request, make_response, abort
from flask_httpauth import HTTPBasicAuth
from werkzeug.security import generate_password_hash, check_password_hash

app = Flask(__name__)
# 创建 HTTPBasicAuth 实例
auth = HTTPBasicAuth()

# 模拟的用户数据库
# 在实际应用中,您应该使用数据库来存储用户信息
# 这里我们使用字典来模拟
user_db = {
    "john": generate_password_hash("hello"),  # 存储密码的散列值
    "susan": generate_password_hash("bye")
}

# 使用 verify_password 装饰器注册验证密码的函数
@auth.verify_password
def verify_password(username, password):
    # 检查用户名是否存在于模拟数据库中
    if username in user_db:
        # 检查密码是否匹配存储的散列值
        if check_password_hash(user_db[username], password):
            return username
    return None

# 定义一个受保护的路由
@app.route('/')
@auth.login_required  # 使用 HTTPBasicAuth 的 login_required 装饰器
def index():
    # 如果用户已认证,返回成功消息
    auth = request.authorization
    return jsonify({'message': f'Hello, {auth.username}! You are successfully authenticated.'})

# 错误处理,当认证失败时返回 401 错误
@auth.error_handler
def unauthorized():
    return make_response(jsonify({'error': 'Unauthorized access'}), 401)

if __name__ == '__main__':
    # 启动 Flask 应用
    app.run(debug=True)

日终

def logit(func):
    @wraps(func)
    def with_logging(*args,**kwargs):
        print(func.__name__+"was called")
        return func(*args,**kwargs)
    return with_logging
@logit
def addition_func(x):
    return x+x
result = addition_func(4)
addition_funcwas called
result
8

@wraps接受一个函数来进行装饰,并加入了复制函数名称、注释文档、参数列表等功能。可以让我们在装饰器里面访问在装饰之前的函数的属性。

对象变动 Mutation

def add_to(n,target=[]):
    target.append(n)
    return target
add_to(1)
[1]
add_to(1)
[1, 1]
add_to(1)
[1, 1, 1]
def add_to_new(n,target_new=None):
    if target_new is None:
        target_new = []
    target_new.append(n)
    return target_new
add_to_new(1)
[1]
add_to_new(1)
[1]
add_to_new(1)
[1]

__slots__魔法

# 不使用__slots__
class MyClass(object):
    def __init__(self,name,identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()
# 使用__slots__
# 减少内存占用
class MyClass(object):
    __slots__ = ['name','identifier']
    def __init__(self,name,identifier):
        self.name = name
        self.identifier = identifier
        self.set_up()

容器(Collections)

defaultdict

例一

from collections import defaultdict

numbers = (
    ('aaa','1'),
    ('bbb','2'),
    ('ccc','3'),
    ('ddd','4'),
    ('eee','5'),
    ('fff','6'),
)

floor_number = defaultdict(list)

for name,num in numbers:
    floor_number[name].append(num)

print(floor_number)
defaultdict(<class 'list'>, {'aaa': ['1'], 'bbb': ['2'], 'ccc': ['3'], 'ddd': ['4'], 'eee': ['5'], 'fff': ['6']})

例二

import collections
# 定义递归的 defaultdict 树结构
tree = lambda:collections.defaultdict(tree)
# 创建树的根节点
some_dict = tree()
# 添加一些节点
some_dict['mumbers']['favourite'] = "4"
import json
print(json.dumps(some_dict))
{"mumbers": {"favourite": "4"}}

Counter

# Counter是一个计数器,可以帮我们针对某项数据进行计算。
from collections import Counter

# 计数元素
words = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']
word_counts = Counter(words)

print(word_counts)
Counter({'apple': 3, 'banana': 2, 'orange': 1})

Deque

# dque提供了一个双端队列,可以从头\尾两端添加或者删除元素。
from collections import deque

# 创建双端队列
dq = deque()

# 添加元素
dq.append('a')  # 在右侧添加
dq.append('b')  # 在右侧添加
dq.append('c')  # 在右侧添加
dq.appendleft('z')  # 在左侧添加

print(dq)

# 弹出元素
print(dq.pop())
print(dq.popleft())
deque(['z', 'a', 'b', 'c'])
c
z
print(dq.popleft())
a
print(dq.popleft())
b

NamedTuple

namedtuple 是 tuple 的子类,允许你创建带有命名字段的元组。

例一

# 从 collections 模块导入 namedtuple 工厂函数
from collections import namedtuple

# 使用 namedtuple 创建一个名为 Man 的新类型
# Man 是一个元组,拥有三个命名字段:name(名字)、age(年龄)和 high(身高)
Man = namedtuple('Man', ['name', 'age', 'high'])

# 创建一个 Man 类型的新实例,名为 zhouwp
# 在这里,我们为 Man 类型的三个字段分别赋值:
# - name: "zhouwp",表示这个人的名字是 zhouwp
# - age: 38,表示这个人的年龄是 38 岁
# - high: 164,表示这个人的身高是 164 厘米
zhouwp = Man(name='zhouwp', age=38, high='164cm')

# 打印 zhouwp 对象,它是一个 Man 类型的实例
# 由于 Man 是 namedtuple 的一个子类,实例将按照定义的顺序打印字段名和值
zhouwp
Man(name='zhouwp', age=38, high='164cm')

例二

from collections import namedtuple

# 创建命名元组类型
Point = namedtuple('Point', ['x', 'y'])

# 创建命名元组
p = Point(11, y=22)

print(p.x)
print(p.y)
print(p)
11
22
Point(x=11, y=22)

枚举 Enumerate

enumerate() 函数返回的是一个元组,第一个元素是索引,第二个元素是可迭代对象的元素。

my_list = ['apple', 'banana', 'grapes', 'pear']

for counter,value in enumerate(my_list):
    print(counter,value)
0 apple
1 banana
2 grapes
3 pear
for counter,value in enumerate(my_list,2):# 其中2表示从数字2开始枚举
    print(counter,value)
2 apple
3 banana
4 grapes
5 pear

创建包含索引的元组列表

couter_list = list(enumerate(my_list,1))
couter_list
[(1, 'apple'), (2, 'banana'), (3, 'grapes'), (4, 'pear')]

案例一

在管理一个投资组合时,分析每个资产的表现。

# 假设这是一个投资组合中不同资产的回报率
portfolio_returns = {'Stock A': 0.08, 'Stock B': -0.05, 'Bond': 0.03, 'Commodity': 0.12}

# 获取资产名称列表
assets = list(portfolio_returns.keys())

# 分析每个资产的回报率
for index, asset in enumerate(assets, 1):
    return_rate = portfolio_returns[asset]
    print(f"资产 {index}: {asset}: 回报收益率:{return_rate:.2%}")
资产 1: Stock A: 回报收益率:8.00%
资产 2: Stock B: 回报收益率:-5.00%
资产 3: Bond: 回报收益率:3.00%
资产 4: Commodity: 回报收益率:12.00%
portfolio_returns.keys()
dict_keys(['Stock A', 'Stock B', 'Bond', 'Commodity'])
portfolio_returns.values()
dict_values([0.08, -0.05, 0.03, 0.12])

案例二

portfolio_returns = {'Stock A': 0.08, 'Stock B': -0.05, 'Bond': 0.03, 'Commodity': 0.12}

# 分析每个资产的回报率
for asset, return_rate in enumerate(portfolio_returns, 1):
    print(f"资产 {asset}: 回报收益率: {return_rate}")
资产 1: 回报收益率: Stock A
资产 2: 回报收益率: Stock B
资产 3: 回报收益率: Bond
资产 4: 回报收益率: Commodity
type(portfolio_returns)
dict

案例三

# 假设这是连续几天的股票价格列表
stock_prices = [120.50, 121.75, 118.20, 122.45, 123.30]

# 使用enumerate()来获取价格及其索引(天数)
for day, price in enumerate(stock_prices):
    if day == 0:
        print(f"第 {day+1}天: 股价是 {price}")
    else:
        previous_price = stock_prices[day - 1]
        price_change = price - previous_price
        print(f"第 {day+1}天: 股价是 {price}, 相比上一个交易日增长: {price_change:.2f}")
第 1天: 股价是 120.5
第 2天: 股价是 121.75, 相比上一个交易日增长: 1.25
第 3天: 股价是 118.2, 相比上一个交易日增长: -3.55
第 4天: 股价是 122.45, 相比上一个交易日增长: 4.25
第 5天: 股价是 123.3, 相比上一个交易日增长: 0.85

案例四

# 假设这是连续几天的股票价格列表
stock_prices = [120.50, 121.75, 118.20, 122.45, 123.30]

# 使用enumerate()来获取价格及其索引(天数)
for day, price in enumerate(stock_prices):
    if day == 0:
        print(f"第 {day+1} 天: 开盘价: {price}")
    else:
        previous_price = stock_prices[day - 1]
        price_change = (price - previous_price)/previous_price
        print(f"第 {day+1} 天: 价格是: {price}, 相比上一个交易日涨跌幅: {price_change:.2f}%")
第 1 天: 开盘价: 120.5
第 2 天: 价格是: 121.75, 相比上一个交易日涨跌幅: 0.01%
第 3 天: 价格是: 118.2, 相比上一个交易日涨跌幅: -0.03%
第 4 天: 价格是: 122.45, 相比上一个交易日涨跌幅: 0.04%
第 5 天: 价格是: 123.3, 相比上一个交易日涨跌幅: 0.01%

对象自省

stock_prices_new = [120.50, 121.75, 118.20, 122.45,122.45, 123.30]
type(stock_prices_new)
list
len(stock_prices_new)
6
stock_prices_new
[120.5, 121.75, 118.2, 122.45, 122.45, 123.3]

dir

列出⼀个对象所拥有的属性和⽅法。

dir(stock_prices_new)
['__add__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getstate__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__imul__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rmul__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'append',
 'clear',
 'copy',
 'count',
 'extend',
 'index',
 'insert',
 'pop',
 'remove',
 'reverse',
 'sort']
# 返回元素在列表中出现的次数
stock_prices_new.count(122.45)
2

inspect模块

import inspect
print(inspect.getmembers(str))
[('__add__', <slot wrapper '__add__' of 'str' objects>), ('__class__', <class 'type'>), ('__contains__', <slot wrapper '__contains__' of 'str' objects>), ('__delattr__', <slot wrapper '__delattr__' of 'object' objects>), ('__dir__', <method '__dir__' of 'object' objects>), ('__doc__', "str(object='') -> str\nstr(bytes_or_buffer[, encoding[, errors]]) -> str\n\nCreate a new string object from the given object. If encoding or\nerrors is specified, then the object must expose a data buffer\nthat will be decoded using the given encoding and error handler.\nOtherwise, returns the result of object.__str__() (if defined)\nor repr(object).\nencoding defaults to sys.getdefaultencoding().\nerrors defaults to 'strict'."), ('__eq__', <slot wrapper '__eq__' of 'str' objects>), ('__format__', <method '__format__' of 'str' objects>), ('__ge__', <slot wrapper '__ge__' of 'str' objects>), ('__getattribute__', <slot wrapper '__getattribute__' of 'str' objects>), ('__getitem__', <slot wrapper '__getitem__' of 'str' objects>), ('__getnewargs__', <method '__getnewargs__' of 'str' objects>), ('__getstate__', <method '__getstate__' of 'object' objects>), ('__gt__', <slot wrapper '__gt__' of 'str' objects>), ('__hash__', <slot wrapper '__hash__' of 'str' objects>), ('__init__', <slot wrapper '__init__' of 'object' objects>), ('__init_subclass__', <built-in method __init_subclass__ of type object at 0x00007FFB51E79F30>), ('__iter__', <slot wrapper '__iter__' of 'str' objects>), ('__le__', <slot wrapper '__le__' of 'str' objects>), ('__len__', <slot wrapper '__len__' of 'str' objects>), ('__lt__', <slot wrapper '__lt__' of 'str' objects>), ('__mod__', <slot wrapper '__mod__' of 'str' objects>), ('__mul__', <slot wrapper '__mul__' of 'str' objects>), ('__ne__', <slot wrapper '__ne__' of 'str' objects>), ('__new__', <built-in method __new__ of type object at 0x00007FFB51E79F30>), ('__reduce__', <method '__reduce__' of 'object' objects>), ('__reduce_ex__', <method '__reduce_ex__' of 'object' objects>), ('__repr__', <slot wrapper '__repr__' of 'str' objects>), ('__rmod__', <slot wrapper '__rmod__' of 'str' objects>), ('__rmul__', <slot wrapper '__rmul__' of 'str' objects>), ('__setattr__', <slot wrapper '__setattr__' of 'object' objects>), ('__sizeof__', <method '__sizeof__' of 'str' objects>), ('__str__', <slot wrapper '__str__' of 'str' objects>), ('__subclasshook__', <built-in method __subclasshook__ of type object at 0x00007FFB51E79F30>), ('capitalize', <method 'capitalize' of 'str' objects>), ('casefold', <method 'casefold' of 'str' objects>), ('center', <method 'center' of 'str' objects>), ('count', <method 'count' of 'str' objects>), ('encode', <method 'encode' of 'str' objects>), ('endswith', <method 'endswith' of 'str' objects>), ('expandtabs', <method 'expandtabs' of 'str' objects>), ('find', <method 'find' of 'str' objects>), ('format', <method 'format' of 'str' objects>), ('format_map', <method 'format_map' of 'str' objects>), ('index', <method 'index' of 'str' objects>), ('isalnum', <method 'isalnum' of 'str' objects>), ('isalpha', <method 'isalpha' of 'str' objects>), ('isascii', <method 'isascii' of 'str' objects>), ('isdecimal', <method 'isdecimal' of 'str' objects>), ('isdigit', <method 'isdigit' of 'str' objects>), ('isidentifier', <method 'isidentifier' of 'str' objects>), ('islower', <method 'islower' of 'str' objects>), ('isnumeric', <method 'isnumeric' of 'str' objects>), ('isprintable', <method 'isprintable' of 'str' objects>), ('isspace', <method 'isspace' of 'str' objects>), ('istitle', <method 'istitle' of 'str' objects>), ('isupper', <method 'isupper' of 'str' objects>), ('join', <method 'join' of 'str' objects>), ('ljust', <method 'ljust' of 'str' objects>), ('lower', <method 'lower' of 'str' objects>), ('lstrip', <method 'lstrip' of 'str' objects>), ('maketrans', <built-in method maketrans of type object at 0x00007FFB51E79F30>), ('partition', <method 'partition' of 'str' objects>), ('removeprefix', <method 'removeprefix' of 'str' objects>), ('removesuffix', <method 'removesuffix' of 'str' objects>), ('replace', <method 'replace' of 'str' objects>), ('rfind', <method 'rfind' of 'str' objects>), ('rindex', <method 'rindex' of 'str' objects>), ('rjust', <method 'rjust' of 'str' objects>), ('rpartition', <method 'rpartition' of 'str' objects>), ('rsplit', <method 'rsplit' of 'str' objects>), ('rstrip', <method 'rstrip' of 'str' objects>), ('split', <method 'split' of 'str' objects>), ('splitlines', <method 'splitlines' of 'str' objects>), ('startswith', <method 'startswith' of 'str' objects>), ('strip', <method 'strip' of 'str' objects>), ('swapcase', <method 'swapcase' of 'str' objects>), ('title', <method 'title' of 'str' objects>), ('translate', <method 'translate' of 'str' objects>), ('upper', <method 'upper' of 'str' objects>), ('zfill', <method 'zfill' of 'str' objects>)]
type(inspect.getmembers(str))
list
import pandas as pd
data = inspect.getmembers(str)
df = pd.DataFrame(data)
df
0 1
0 __add__ <slot wrapper '__add__' of 'str' objects>
1 __class__ <class 'type'>
2 __contains__ <slot wrapper '__contains__' of 'str' objects>
3 __delattr__ <slot wrapper '__delattr__' of 'object' objects>
4 __dir__ <method '__dir__' of 'object' objects>
... ... ...
76 swapcase <method 'swapcase' of 'str' objects>
77 title <method 'title' of 'str' objects>
78 translate <method 'translate' of 'str' objects>
79 upper <method 'upper' of 'str' objects>
80 zfill <method 'zfill' of 'str' objects>

81 rows × 2 columns

推导式

列表推导式 list comprehensions

规范

multiple = [i for i in range(30) if i%3 is 0]
multiple
[0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
# 快速生成列表
# 普通方法
squared_1 = []
for x in range(10):
    squared_1.append(x**2)
squared_1
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# 列表推导式方法
squared_2 = [x**2 for x in range(10)]
squared_2
[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

字典推导式 dict comprehensions

mcase = {'a': 10, 'b': 34, 'A': 7, 'Z': 3}
# 使用字典推导式创建一个新的字典,其中所有键都是小写的
lowercase_mcase = {key.lower(): value for key, value in mcase.items()}
lowercase_mcase
{'a': 7, 'b': 34, 'z': 3}

集合推导式 set comprehensions

multiple_set = {i for i in range(30) if i%3 is 0}
multiple_set
{0, 3, 6, 9, 12, 15, 18, 21, 24, 27}

finally从句

try:
    xxxxx
except IOError as e:
    xxxxx
finally:
    xxxxx

try/else 从句

try:
    xxxxx
except Exception:
    xxxxx
else:
    xxxxx
finally:
    xxxxx

lambda表达式

a = [(1,2),(4,1),(9,10),(13,-3)]
a.sort(key=lambda x:x[0])
a
[(1, 2), (4, 1), (9, 10), (13, -3)]
a.sort(key=lambda x:x[1])
a
[(13, -3), (4, 1), (1, 2), (9, 10)]

open函数

with open(file, mode) as variable:
    file: 要打开的文件的路径。
    mode: 打开文件的模式,常见的模式有:
        'r': 读取模式,默认值。
        'w': 写入模式,会覆盖文件内容。
        'a': 追加模式,会在文件末尾追加内容。
        'b': 二进制模式,用于读写二进制文件。
        '+': 更新模式,可以读写文件。
    variable: 打开的文件对象的变量名。

文本文件

读取文本文件

with open('text.txt','r',encoding='utf-8') as f:
    content = f.read()
    print(content)
First line
Second line
Third line
文平

写入文本文件

with open('text.txt','w',encoding='utf-8') as f:
    f.write('你你好你好你好\n你好你好你好你好好\n')
with open(f'd:/Notebook/Test/text.txt','r',encoding='utf-8') as f:
    content = f.read()
    print(content)
First line
Second line
Third line

追加内容到文本文件

with open('text.txt','a',encoding='utf-8') as f:
    f.write('文平')
with open(f'd:/Notebook/Test/text.txt','r',encoding='utf-8') as f:
    content = f.read()
    print(content)
First line
Second line
Third line

写入多行到文本文件

lines = ['First line', 'Second line', 'Third line']
with open('text.txt','w',encoding='utf-8') as file:
    for line in lines:
        file.write(line + '\n')  # 每个line后面添加换行符

逐行读取文本文件

with open('text.txt','r',encoding='utf-8') as file:
    for line in file:
        print(line.strip())  # 使用strip()去除行尾的换行符
First line
Second line
Third line

二进制文件

### 读取二进制文件
with open('image.png','rb') as f:
    data = f.read()
    print(data)
b'\xff\xd8\xff\xe0\x00\x10JFIF\x00\x01\x01\x00\x00\x01\x00\x01\x00\x00\xff\xdb\x00C\x00\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xff\xdb\x00C\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\x01\xff\xc0\x00\x11\x08\x00?\x00\xaa\x03\x01"\x00\x02\x11\x01\x03\x11\x01\xff\xc4\x00\x15\x00\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\n\xff\xc4\x00\x14\x10\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x01\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xc4\x00\x14\x11\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xda\x00\x0c\x03\x01\x00\x02\x11\x03\x11\x00?\x00\xbf\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1f\xff\xd9'
with open('image.png', 'r+b') as f:
    # 假设我们要更新文件中的某些数据
    f.seek(0)  # 移动到文件开头
    data = f.read(10)  # 读取前10个字节
    modified_data = data.replace(b'old', b'new')  # 修改数据
    f.seek(0)  # 重新移动到文件开头
    f.write(modified_data)  # 写入修改后的数据

CSV文件

# 写入CSV文件
import csv

rows = [
    ['姓名', '年龄', '职业'],
    ['张三', '28', '工程师'],
    ['李四', '35', '设计师']
]

with open('output.csv', 'w', newline='', encoding='utf-8') as file:
    writer = csv.writer(file)
    writer.writerows(rows)
# 读取CSV文件
import csv

with open('output.csv', 'r', newline='', encoding='utf-8') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)  # 每行作为一个列表打印
['姓名', '年龄', '职业']
['张三', '28', '工程师']
['李四', '35', '设计师']

JSON文件

写入JSON文件

import json

# 数据字典
data = {
    "name": "张三",
    "age": 30,
    "city": "北京"
}

# 写入JSON文件
with open('output.json', 'w', encoding='utf-8') as file:
    json.dump(data, file, ensure_ascii=False, indent=4)

读取JSON文件

import json

# 读取JSON文件
with open('output.json', 'r', encoding='utf-8') as file:
    data = json.load(file)
    print(data)
{'name': '张三', 'age': 30, 'city': '北京'}

XML文件

写入XML文件

import xml.etree.ElementTree as ET

# 创建XML元素
root = ET.Element("data")
child = ET.SubElement(root, "item", attrib={"key": "value"})
child.text = "Example"

# 写入XML文件
tree = ET.ElementTree(root)
tree.write('output.xml', encoding='utf-8', xml_declaration=True)

读取XML文件

import xml.etree.ElementTree as ET

# 读取XML文件
tree = ET.parse('output.xml')
root = tree.getroot()

for child in root:
    print(child.tag, child.attrib)
item {'key': 'value'}

Excel文件

写入Excel文件(使用pandas)

import pandas as pd

# 创建DataFrame
df = pd.DataFrame({
    "Column1": [1, 2, 3],
    "Column2": ["A", "B", "C"]
})

# 写入Excel文件
df.to_excel('output.xlsx', index=False)

读取Excel文件(使用pandas)

import pandas as pd

# 读取Excel文件
df = pd.read_excel('output.xlsx')

# 打印DataFrame
print(df)
   Column1 Column2
0        1       A
1        2       B
2        3       C

PDF 文件

# 安装PyPDF2
# pip install PyPDF2

from PyPDF2 import PdfReader

# 读取PDF文件
with open('PDF-TEST.pdf', 'rb') as file:
    reader = PdfReader(file)
    for page_num in range(len(reader.pages)):
        print(reader.pages[page_num].extract_text())
大清亡了? 

WORD 文件

# pip install python-docx
from docx import Document

# 创建一个新的Word文档
doc = Document()

# 添加一个新段落
doc.add_paragraph('Hello, World!')

# 添加另一个段落并设置不同的格式
p = doc.add_paragraph('这是另一个段落。')
run = p.add_run('这是粗体和斜体。')
run.bold = True
run.italic = True

# 保存文档
doc.save('document.docx')
from docx import Document

# 打开Word文档
doc = Document('document.docx')

# 打印文档中的每个段落
for para in doc.paragraphs:
    print(para.text)
Hello, World!
这是另一个段落。这是粗体和斜体。

图像文件

from PIL import Image

# 创建一个新的图像
new_img = Image.new('RGB', (100, 100), color = 'red')

# 保存图像文件
new_img.save('image.png')
from PIL import Image

# 打开图像文件
with Image.open('image.png') as img:
    img.show()  # 显示图像

posted @ 2024-06-03 13:26  江雪独钓翁  阅读(4)  评论(0编辑  收藏  举报