博客
关于我
Python3.6学习笔记(二)
阅读量:446 次
发布时间:2019-03-06

本文共 3125 字,大约阅读时间需要 10 分钟。

Python 高级特性

切片

Python 提供了强大的切片功能,类似于Excel 中数据透视表的切片器。通过指定索引范围,可以轻松提取列表中所需的部分数据。

L = ['Michael', 'Sarah', 'Tracy', 'Bob', 'Jack']L[0:3]  # 提取前三个元素:['Michael', 'Sarah', 'Tracy']S = list(range(100))S[0:100:9]  # 提取索引为 9 的倍数的元素:[0, 9, 18, ..., 99]

切片操作不仅适用于列表,还可以用于 tuple:

tuple_list = [1, 2, 3]tuple_result = tuple_list[1:3]  # tuple(2, 3)

迭代

Python 的迭代机制允许对各种可迭代对象(如 list、tuple、dict、str 等)进行统一处理。可通过 for 循环遍历这些对象。

for item in [1, 2, 3]:    print(item)

enumerate 函数可将索引和元素同时遍历:

for index, value in enumerate(['a', 'b', 'c']):    print(f'Index: {index}, Value: {value}')

检查对象是否可迭代:

from collections import Iterableisinstance('abc', Iterable)  # Trueisinstance([1, 2, 3], Iterable)  # Trueisinstance(123, Iterable)  # False

列表生成式

列表生成式(List Comprehensions)是一种强大的工具,用于创建高效的 list。语法简洁,效率高。

tiangan = '甲乙丙丁戊己庚辛壬癸'dizhi = '子丑寅卯辰巳午未申酉戌亥'jiazi = [tiangan[x % len(tiangan)] + dizhi[x % len(dizhi)] for x in range(60)]

支持条件判断和多层循环:

[x * x for x in range(1, 11) if x % 2 == 0]  # [4, 16, 36, 64, 100][m + n for m in 'ABC' for n in 'XYZ']  # ['AX', 'AY', 'AZ', 'BX', 'BY', 'BZ', 'CX', 'CY', 'CZ']

生成器

生成器是一种高效的数据结构,适合处理大数据量的迭代操作。生成器在循环时按需计算,避免了存储所有数据的开销。

L = [x * x for x in range(10)]g = (x * x for x in range(10))  # 生成器对象try:    print(next(g))  # 0    print(next(g))  # 1except StopIteration:    print('结束')

迭代器与生成器

  • 可迭代对象(Iterable):如 list、tuple、dict 等,可以通过 for 循环遍历。
  • 迭代器(Iterator):通过 iter() 函数将可迭代对象转换为迭代器,支持通过 next() 获取下一个元素。

函数式编程

Python 支持函数式编程,通过高阶函数实现函数的组合与传递。

高阶函数

  • 变量可以指向函数

    abs(-10)  # 10f = absf(-10)  # 10
  • 函数名也是变量

    abs = 10print(abs(-10))  # 错误:int object is not callable
  • 传入函数

    def f(x):    return x + 1g = fprint(g(5))  # 6

map、reduce、filter

  • map:将函数作用于序列的每个元素:

    def f(x):    return x * xr = map(f, [1, 2, 3, 4, 5, 6, 7, 8, 9])list(r)  # [1, 4, 9, 16, 25, 36, 49, 64, 81]
  • reduce:对序列进行递归化简:

    from functools import reducedef f(a, b):    return a + br = reduce(f, [1, 2, 3, 4])print(r)  # 10
  • filter:过滤序列:

    def is_odd(n):    return n % 2 == 1filtered = list(filter(is_odd, [1, 2, 4, 5, 6, 9, 10, 15]))print(filtered)  # [1, 5, 9, 15]

排序与闭包

  • sorted:对 list 进行排序:

    sorted_list = sorted([36, 5, -12, 9, -21])print(sorted_list)  # [-21, -12, 5, 9, 36]
  • 闭包(Closure)

    def lazy_sum(*args):    def sum():        total = 0        for n in args:            total += n        return total    return sumsum_func = lazy_sum(1, 2, 3)print(sum_func())  # 6

匿名函数与装饰器

  • 匿名函数(Lambda)

    list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8, 9]))  # [1, 4, 9, 16, 25, 36, 49, 64, 81]
  • 装饰器

    import functoolsdef log(func):    @functools.wraps(func)    def wrapper(*args, **kw):        print(f'call {func.__name__():}')        return func(*args, **kw)    return wrapper@logdef now():    print('2015-3-25')now()  # 输出: call now()

模块与包

  • 模块:一个 .py 文件称为模块。

  • :通过目录组织模块,避免命名冲突。每个包必须包含 __init__.py 文件。

  • 使用模块

    import sysdef test():    args = sys.argv    if len(args) == 1:        print('Hello, world!')    elif len(args) == 2:        print(f'Hello, {args[1]}!')    else:        print('Too many arguments!')if __name__ == '__main__':    test()

作用域与第三方模块

  • 作用域:Python 中的命名作用域分为全局和局部。非公开变量(如 _xxx)不应被直接引用。
  • 安装第三方模块
    pip install Pillow  # 安装第三方库

通过以上内容,可以看到 Python 的高级特性非常强大,适用于不同的编程场景。

转载地址:http://markz.baihongyu.com/

你可能感兴趣的文章
nmap指纹识别要点以及又快又准之方法
查看>>
Nmap渗透测试指南之指纹识别与探测、伺机而动
查看>>
Nmap端口扫描工具Windows安装和命令大全(非常详细)零基础入门到精通,收藏这篇就够了
查看>>
NMAP网络扫描工具的安装与使用
查看>>
NMF(非负矩阵分解)
查看>>
nmon_x86_64_centos7工具如何使用
查看>>
NN&DL4.1 Deep L-layer neural network简介
查看>>
NN&DL4.3 Getting your matrix dimensions right
查看>>
NN&DL4.7 Parameters vs Hyperparameters
查看>>
NN&DL4.8 What does this have to do with the brain?
查看>>
nnU-Net 终极指南
查看>>
No 'Access-Control-Allow-Origin' header is present on the requested resource.
查看>>
NO 157 去掉禅道访问地址中的zentao
查看>>
no available service ‘default‘ found, please make sure registry config corre seata
查看>>
No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?
查看>>
no connection could be made because the target machine actively refused it.问题解决
查看>>
No Datastore Session bound to thread, and configuration does not allow creation of non-transactional
查看>>
No fallbackFactory instance of type class com.ruoyi---SpringCloud Alibaba_若依微服务框架改造---工作笔记005
查看>>
No Feign Client for loadBalancing defined. Did you forget to include spring-cloud-starter-loadbalanc
查看>>
No mapping found for HTTP request with URI [/...] in DispatcherServlet with name ...的解决方法
查看>>