Python 技能提升(一)

cpp 复制代码
```python

```

注释规范

python 复制代码
# Add commit for you codes.
# The proper addition of comments is so beautiful.

from abc import abstractmethod


def add(a: int, b: int) -> int:
    # You can write some necessary notes here.
    # Such as the role of functions, the types and roles of parameters.
    #
    # But what we recommend more is to know the meaning of the name when naming.
    # So you don't have to write too many comments.
    #
    # It's important to remember to update your comments after you change the code.
    return a + b


# The following comments are superfluous.

a = 10  # Define a variable to be 10.
b = 90  # Define a variable to be 90.
res = add(a, b)  # Call the function and get the sum of the two.
print(res)  # Output calculation result

文档字符串规范

python 复制代码
def execute():
    """Execute the action to make the file saved."""
    pass


def test(url: str):
    """This is a test function for string document.
    Some description here.
    Another description here.

    Note: The key point to note.

    Args:
        url: A string where to fetch the content from

    Returns:
        A string with UTF-8 encoded content provided by the site.

    Raises:
        ValueError: if url argument is not of the expected type (str).
    """
    pass


# Output Documentation String
print(execute.__doc__)
print(test.__doc__)

注解规范

python 复制代码
class Circle:
    def __init__(self, radius):
        self.radius = radius
        self.area = 0


def area(radius: float) -> Circle:
    """Compute area of a Circle with given radius."""
    pass


# Show the annotation content of the function
print(area.__annotations__)  # {'radius': <class 'float'>, 'return': <class '__main__.Circle'>}

布局规范

python 复制代码
# Different methods in a class should be separated by empty lines.
# This is more aesthetically pleasing, as in the following example.

class People:
    def eat(self):
        pass

    def walk(self):
        pass
    
python 复制代码
# Appropriate blank lines make the code more elegant.

def calculate_the_number_of_rows_of_content_from(path: str) -> int:
    with open(path, 'r') as file:
        lines = file.readlines()

    count = 0
    for line in lines:
        if line.strip():
            count += 1

    return count
python 复制代码
# A line of code should be limited to 75 characters.
# If you exceed that amount, you can use the "\" symbol to wrap the line.
# Or, if you use the () symbol, you can simply wrap the line.

def some_too_long_method_for_demo_and_specified_usage(first_arg, second_arg, \
                                                      third_arg, fourth_arg):
    pass

too_long_variable_for_demo_in_scenario_one = 1
too_long_variable_for_demo_in_scenario_two = 2
too_long_variable_for_demo_in_scenario_three = 3

result = (too_long_variable_for_demo_in_scenario_one
          + too_long_variable_for_demo_in_scenario_two
          + too_long_variable_for_demo_in_scenario_three)
python 复制代码
# Tabs and 4 Spaces are not equal.
# We recommend using 4 Spaces for indentation instead of tabs.

num = int(input())
if num > 0:
    pass
python 复制代码
# Here is our recommended format.

mylist = [
    1, 2, 3,
    4, 5, 6
]

断言 assert

python 复制代码
def divide(x: int, y: int) -> float:
    assert y != 0, "错误:除数不能为零!"  # 此行代码大意是:我断言y一定不等于0,如果我预判错误,抛出错误字符串
    return x / y


print(divide(2, 0))

符号 _

python 复制代码
for _ in range(5):  # We only care about cycling five times.
    print("Hello World")

my_dict = {'age': 18, 'name': 'Jack', 'hobby': 'code'}
for key, _ in my_dict.items():  # We are only concerned with its key.
    print(key)

Tree = ('green', 'plentiful', 'leaf')
color, _, _ = Tree  # We only care about color.

列表推导式

python 复制代码
class Weight:
    def __init__(self, weight: int):
        self.weight = weight

    def __repr__(self):
        return f'weight: {self.weight}'


weight_instances = [Weight(n) for n in range(10)]
print(weight_instances)

过滤与映射

python 复制代码
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def is_odd_number(number: int) -> bool:  # 判断一个数是否为奇数
    return number % 2 == 1

def multiply_by_two(number: int) -> int:  # 将一个数乘以2
    return number * 2

odd_nums = filter(is_odd_number, nums)  # 过滤出奇数
map_nums = map(multiply_by_two, odd_nums)  # 将奇数乘以2

result = list(map_nums)
print(result)

# 上面代码可以用列表推导式完成

nums = [1, 2, 3, 4, 5, 6, 7, 8, 9]
res_nums = [res * 2 for res in nums if res % 2 == 1]
print(res_nums)

灵活切片与*号

python 复制代码
my_list = ['a', 'b', 'c', 'd', 'e']

# 灵活切片法:

(ele_1, ele_2, remain) = my_list[0], my_list[1], my_list[2:]
print(remain)  # ['c', 'd', 'e']

(ele_1, middle, ele_2) = my_list[0], my_list[1:-1], my_list[-1]
print(middle)  # ['b', 'c', 'd']

(front, ele_1, ele_2) = my_list[0:-2], my_list[-2], my_list[-1]
print(front)  # ['a', 'b', 'c']


# 使用 * 号的方法

(ele_1, ele_2, *remain) = my_list
print(remain)  # ['c', 'd', 'e']

(ele_1, *middle, ele_2) = my_list
print(middle)  # ['b', 'c', 'd']

(*front, ele_1, ele_2) = my_list
print(front)  # ['a', 'b', 'c']

模拟 switch-case

python 复制代码
import operator  # 内置模块


def calculator(var1, var2, symbol):
    operator_dict = {
        '+': operator.add,  # operator 模块里面的 加法函数
        '-': operator.sub,  # operator 模块里面的 减法函数
        '*': operator.mul,  # operator 模块里面的 乘法函数
        '/': operator.truediv  # operator 模块里面的 除法函数
    }
    return operator_dict.get(symbol)(var1, var2)  # 函数地址 + 括号 => 调用


print(calculator(10, 20, '*'))  # 200

温馨提示:在 Python 3.10 推出了 match-case,其功能比其他语言的 switch-case 更强大

推荐阅读:https://blog.csdn.net/wuShiJingZuo/article/details/134589275

装饰器 @dataclass

推荐阅读:https://www.cnblogs.com/wang_yb/p/18077397

python 复制代码
from dataclasses import dataclass


@dataclass
class People:
    pass

字典推导式

python 复制代码
from dataclasses import dataclass


@dataclass
class User:
    name: str
    email: str


list_of_users = [User('Bob', '168@qq.com'), User('Jack', '195@qq.com')]


# 普通的写法
emails_for_user = {}
for user in list_of_users:
    if user.email:
        emails_for_user[user.name] = user.email

print(emails_for_user)


# 字典推导的写法
emails_for_user = {user.name: user.email
                   for user in list_of_users if user.email}
print(emails_for_user)

字典的排序

python 复制代码
d = {'a': 400, 'c': 200, 'b': 300, 'd': 100}
print(d.items())  # dict_items([('a', 400), ('c', 200), ('b', 300), ('d', 100)])


# 按照键进行排序(升序)
d_list = sorted(d.items())
print(d_list)  # [('a', 400), ('b', 300), ('c', 200), ('d', 100)]


# 按照值进行排序(升序)
rule = lambda x: x[1]
d_list = sorted(d.items(), key=rule)  # 这里的key的意思不是字典中的key,而是sorted()函数的一个参数,用来说明以哪个东西进行排序
print(d_list)  # [('d', 100), ('c', 200), ('b', 300), ('a', 400)]


# 按照值进行排序(降序)
d_list = sorted(d.items(), key=lambda x: x[1], reverse=True)
print(d_list)  # [('a', 400), ('b', 300), ('c', 200), ('d', 100)]

字典的组合

python 复制代码
fruits_price_1 = {'apple': 10.5, 'orange': 8.8}
fruits_price_2 = {'banana': 2.8, 'orange': 9.5}
fruits_price_3 = {'watermelon': 5.5, 'orange': 10.8}

# 通过更新将字典组合起来
lastest_fruit_price = {}
lastest_fruit_price.update(fruits_price_1)
lastest_fruit_price.update(fruits_price_2)
lastest_fruit_price.update(fruits_price_3)
print(lastest_fruit_price)  # {'apple': 10.5, 'orange': 10.8, 'banana': 2.8, 'watermelon': 5.5}

# 使用星星符号**将字典组合起来(速度会更快,因为它背后做了优化)
lastest_fruit_price = {}
lastest_fruit_price = {
    **fruits_price_1,
    **fruits_price_2,
    **fruits_price_3
}
print(lastest_fruit_price)  # {'apple': 10.5, 'orange': 10.8, 'banana': 2.8, 'watermelon': 5.5}

优美的打印字典

python 复制代码
from pprint import pprint

books_map = {'name': 'Python编程指南', 'author': 'Jack',
             'stars': 5, 'release-time': '2024-5-20',
             'info': {'content': 'Guide to Programming ', 'user': 1000}}

pprint(books_map)

"""
运行结果:

{'author': 'Jack',
 'info': {'content': 'Guide to Programming ', 'user': 1000},
 'name': 'Python编程指南',
 'release-time': '2024-5-20',
 'stars': 5}
 
"""

集合的运算

python 复制代码
# 定义两个集合
programming_languages = {'C#', 'Go', 'Java', 'Python', 'Ruby'}
dynamic_languages = {'Ruby', 'Python', 'JavasScript', 'Lua'}

# 集合的
print(programming_languages | dynamic_languages)  # 并集
print(programming_languages & dynamic_languages)  # 交集
print(programming_languages - dynamic_languages)  # 差集1
print(dynamic_languages - programming_languages)  # 差集2
print(programming_languages ^ dynamic_languages)  # 对称差集

"""
运行结果:

{'Python', 'Lua', 'Ruby', 'Java', 'Go', 'C#', 'JavasScript'}
{'Ruby', 'Python'}
{'Go', 'C#', 'Java'}
{'JavasScript', 'Lua'}
{'Lua', 'Java', 'Go', 'C#', 'JavasScript'}

"""

# -------------- 案例演示 --------------

backend_developers = ['John', 'Rose', 'Jane', 'Steven']  # 前端人员
frontend_developers = ['Jack', 'Rose', 'Jane', 'Tom']  # 后端人员
full_stack_developers = []  # 全栈人员

# 筛选出全栈人员:

# 原始方法:
for developer in backend_developers:
    if developer in frontend_developers:
        full_stack_developers.append(developer)

# 利用集合的运算性质
full_stack_developers = list(set(backend_developers) & set(frontend_developers))

集合推导式

python 复制代码
class Person:
    def __init__(self, name):
        self.name = name


person_list = [Person('Jack'), Person(None), Person('Tom'), Person('John'), Person(None)]
name_set = {person.name for person in person_list if person.name}
print(type(name_set), name_set)  # <class 'set'> {'Tom', 'Jack', 'John'}

集合处理 Counter

python 复制代码
from collections import Counter

c = Counter("你好,世界!你好,编程")

print(c)
print(c.most_common(3))  # 出现最多共同点中的前3个
print(c.keys())
print(c.values())
print(list(c.elements()))

"""
运行结果:

Counter({'你': 2, '好': 2, ',': 2, '世': 1, '界': 1, '!': 1, '编': 1, '程': 1})
[('你', 2), ('好', 2), (',', 2)]
dict_keys(['你', '好', ',', '世', '界', '!', '编', '程'])
dict_values([2, 2, 2, 1, 1, 1, 1, 1])
['你', '你', '好', '好', ',', ',', '世', '界', '!', '编', '程']
"""

元组解包数据

python 复制代码
# 使用元组解包数据
csv_file_row = ['Jack', '168@qq.com', 35]
(name, email, age) = csv_file_row
print(name, email, age)  # Jack 168@qq.com 35

# 使用 *元组 解包数据
group1 = ('Cat', 'Dog')
group2 = ('Eagle', 'Geese')
new_group = (*group1, *group2, 'Snake')
print(new_group)  # ('Cat', 'Dog', 'Eagle', 'Geese', 'Snake')


# 使用 *元组 解包数据
def display_users(*users):
    print(type(users))
    for user in users:
        print(user)


display_users('Dany', 'Bobby', 'Jacky')

# 运行结果:
# <class 'tuple'>
# Dany
# Bobby
# Jacky

元组与占位符_

python 复制代码
# 巧用占位符
animal = ('Cat', 'Dog', 'Eagle', 'Geese', 'Tiger')

(first, second, _, _, _,) = animal
print(first, second)  # Cat Dog

(first, second, *_) = animal
print(first, second)  # Cat Dog

高效拼接字符串

python 复制代码
list_of_str = ['Syntax Error', 'Network Error', 'File not found']

# 普通方法
concat_string = ''
for substring in list_of_str:
    concat_string += substring

# 高效方法
concat_string = ''.join(list_of_str)
相关推荐
数据智能老司机4 小时前
精通 Python 设计模式——分布式系统模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——并发与异步模式
python·设计模式·编程语言
数据智能老司机5 小时前
精通 Python 设计模式——测试模式
python·设计模式·架构
数据智能老司机5 小时前
精通 Python 设计模式——性能模式
python·设计模式·架构
c8i5 小时前
drf初步梳理
python·django
每日AI新事件5 小时前
python的异步函数
python
这里有鱼汤6 小时前
miniQMT下载历史行情数据太慢怎么办?一招提速10倍!
前端·python
databook15 小时前
Manim实现脉冲闪烁特效
后端·python·动效
程序设计实验室16 小时前
2025年了,在 Django 之外,Python Web 框架还能怎么选?
python
倔强青铜三17 小时前
苦练Python第46天:文件写入与上下文管理器
人工智能·python·面试