再梳理一遍 Python 系列知识点,夯实基础,无他,唯手熟尔

Python 系列总结都是我自己平时的学习笔记,如果有不正确的地方,希望各位佬儿哥指正纠偏🤗

# 列表数据越多效果越明显
VALID_NAMES = ['pip', 'lili', 'name']

VALID_NAMES_SET = set(VALID_NAMES)

def validate_name(name):
    if name not in VALID_NAMES_SET:
        raise ValueError(f'{name} is not a valid name')
nums = [10, 2, 3, 21, 10, 3]

def ordered_dict(member: list[int]):
    from collections import OrderedDict
    result = list(OrderedDict.fromkeys(member).keys())
    return result

print(ordered_dict(nums))
----------------------------------------------------
[10, 2, 3, 21]
from typing import NamedTuple

class Address(NamedTuple):
    """地址信息结果"""
    country: str
    province: str
    city: str

def latlon_to_address(lat, lon):
    return Address(
        country = country,
        province=  province,
        city = city,
    )
addr = latlon_to_address(lat, lon)
# 通过属性名来使用addr
# addr.city / addr.country / addr.province
from itertools import product

print(list(product([1,2],[3,4])))
----------------------------------------
[(1, 3), (1, 4), (2, 3), (2, 4)]
# 常用多层嵌套循环
def find_twelve(nem_list1, num_list2, num_list3):
    "从这三个数字列表中,寻找是否存在和为12的3个数"
    for num1 in num_list1:
        for num2 in num_list2:
            for num3 in num_list3:
                 if num1 + num2 + num3 == 12:
                    return num1, num2, num3

# 使用product()扁平化多层嵌套循环
from itertools import product

def find_tewlve_v2(num_list1, num_list2, num_list3):
    for num1, num2, num3 in product(num_list1, num_list2, num_list3):
        if num1 + num2 + num3 == 12:
            return num1, num2, num3
# 方法1:使用enumerate
def parse_titles(filename):
    """从各行数据文件中取数据"""
    with open(filename, 'r') as fp:
        for i, line in enumerate(fp):
            if i % 2 == 0:
                yield line

if __name__ == '__main__':
    message_generator = parse_titles('logs.txt')
    while True:
        try:
            print(next(message_generator))
        except StopIteration as e:
            break

但如果需求变更为每隔 3 行读取或者每隔 4 行读取,那我们按照以上的写法应该怎么筛选呢?

# 方法2:使用islice
from itertools import islice

def parse_titles_v2(filename):
    """使用slice实现隔行取值"""
    with open(filename, 'r') as fp:
        for line in islice(fp, 0, None, 2): # islice(seq, start, end, step)
            yield line

if __name__ == '__main__':
    message_generator = parse_titles_v2('logs.txt')
    while True:
        try:
            print(next(message_generator))
        except StopIteration as e:
            break

如果需求变更为每隔 3 行读取或者每隔 4 行读取,我们只需要将 islice(seq, start, end, step) 中的 step 改成 3 或者 4 就行了

测试基础-Python 篇 问&答①


↙↙↙阅读原文可查看相关链接,并与作者交流