首页 > 编程语言 >Study Plan For Python - Part4

Study Plan For Python - Part4

时间:2024-08-26 20:24:29浏览次数:7  
标签:__ Python Study 0.1 Part4 模块 print import self

格式化输出

1.reprlib 模块

提供了一个定制化版本的 repr() 函数,用于缩略显示大型或深层嵌套的容器对象

import reprlib
reprlib.repr(set('fantabulouslywonderificentamazingness')) # 可迭代对象,输出 "{'a', 'b', 'c', 'd', 'e', 'f', ...}"

2.pprint 模块

提供了更加复杂的打印控制,其输出的内置对象和用户自定义对象能够被解释器直接读取

具有美化输出机制

import pprint
t = [[[['black', 'pink'], 'white', ['green', 'red']], [['magenta',
    'yellow'], 'blue']]]

pprint.pprint(t, width=40)

3.textwrap 模块

格式化文本段落,以适应给定的屏幕宽度

import textwrap
doc = """The splitlines() method is just like split('\n') except that it returns a list of strings instead of a list of substrings based on a specific delimiter. It separates a string into lines based on the actual line breaks in the text."""

print(textwrap.fill(doc, width=40))

4.locale 模块

处理与特定地域文化相关的数据格式

import locale
locale.setlocale(locale.LC_ALL, 'English_United States.1252')

conv = locale.localeconv()          # 获取当前地域的文化惯例映射
x = 1234567.8
locale.format_string("%d", x, grouping=True)

locale.format_string("%s%.*f", (conv['currency_symbol'],
                     conv['frac_digits'], x), grouping=True)

模板

1.string 模块

提供了一个通用的 Template 类,允许用户在不更改应用逻辑的情况下定制自己的应用

格式化操作通过占位符实现,$$ 将被转义成单个字符 $

from string import Template

t = Template('${city}市民为$organization捐赠了$$100。')
t.substitute(city='广东', organization='希望工程')
t.safe_substitute(organization='希望工程') # 如果数据缺失,保留占位符原样

# 对一组照片文件进行批量重命名
import time, os.path
photofiles = ['img_1.jpg', 'img_2.jpg', 'img_3.jpg']
class BatchRename(Template):
    delimiter = '%' # 自定义分隔符

fmt = input('Enter rename style (%d-date %n-seqnum %f-format):  ')

t = BatchRename(fmt)
date = time.strftime('%d%b%y')
for i, filename in enumerate(photofiles):
    base, ext = os.path.splitext(filename)
    newname = t.substitute(d=date, n=i, f=ext)
    print('{0} ---> {1}'.format(filename, newname))

使用二进制数据记录格式

1.struct 模块

处理不定长度的二进制记录格式

# 不便用zipfile模块。读取一个ZIP文件,并解析其中的前三个文件头信息
import struct

with open('Archive.zip', 'rb') as f: # 只读,二进制
    data = f.read()

start = 0
for i in range(3):                      
    start += 14 # 将当前位置向后移动 14 个字节,跳过一些固定的字节以到达文件头的起始位置
    fields = struct.unpack('<IIIHH', data[start:start+16]) # 三个无符号整数和两个无符号短整数
    crc32, comp_size, uncomp_size, filenamesize, extra_size = fields

    start += 16 # 将当前位置再向后移动 16 个字节
    filename = data[start:start+filenamesize] # 对应ZIP文件中当前文件的文件名
    start += filenamesize
    extra = data[start:start+extra_size] # 额外数据
    print(filename, hex(crc32), comp_size, uncomp_size) # 文件名、CRC32 值的十六进制表示、压缩后大小和未压缩大小

    start += extra_size + comp_size     

多线程

1.threading 模块

# 一个自定义的线程类AsyncZip,用于在后台异步地将一个文件压缩为 ZIP 文件
import threading, zipfile

class AsyncZip(threading.Thread):
    def __init__(self, infile, outfile):
        threading.Thread.__init__(self)
        self.infile = infile
        self.outfile = outfile

    def run(self):
        f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED)
        f.write(self.infile)
        f.close()
        print('Background zip has completed.')

background = AsyncZip('data.txt', 'archive.zip')
background.start()
print('The main program is proceeding in the foreground.')

background.join()    
print('The main program has waited until background was finished.')

日志记录

1.logging 模块

提供日志记录系统

import logging # 级别:debug > info > warning > error > critical
logging.debug('Debugging information')
logging.info('Informational message')
logging.warning('Warning:config file %s not found', 'server.conf')
logging.error('Error occurred')
logging.critical('Critical error -- shutting down') # 严重错误

弱引用

1.weakref 模块

提供了对弱引用的支持

import weakref, gc
class A:
    def __init__(self, value):
        self.value = value
    def __repr__(self):
        return str(self.value)

a = A(10)                  
d = weakref.WeakValueDictionary() # 其中的值是弱引用
d['primary'] = a            # 不创建a的额外强引用,而是存储弱引用
d['primary']                

del a                       
gc.collect()                

d['primary']                # 仅被弱引用时,这个对象可以被垃圾回收   

用于操作列表的工具

1.array 模块

from array import array # array,只能存储类型一致的数据且存储密度更高
a = array('H', [3000, 10, 600, 3333333]) 
sum(a)

a[1:3]

2.collections 模块

from collections import deque # deque,高效的两端插入和删除操作
d = deque(["a", "b", "c"]) # 双端队列
d.append("d")
print("Handling", d.popleft())

# 广度优先搜索算法
from collections import deque

graph = { # 字典
    'A': ['B', 'C'],
    'B': ['D', 'E'],
    'C': ['F'],
    'D': [],
    'E': ['F'],
    'F': []
}

def bfs(graph, start):
    visited = set()
    queue = deque([start])
    visited.add(start)
    while queue:
        node = queue.popleft()
        print(node)
        for neighbor in graph[node]:
            if neighbor not in visited:
                queue.append(neighbor)
                visited.add(neighbor)

3.bisect 模块

有序列表中快速插入

import bisect
scores = [(1, 'a'), (2, 'b'), (4, 'c'), (5, 'd')]
bisect.insort(scores, (3, 'e'))
scores # 输出 [(1, 'a'), (2, 'b'), (3, 'c'), (4, 'e'), (5, 'd')]

4.heapq 模块

提供了堆数据结构的实现

from heapq import heapify, heappop, heappush
data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0]
heapify(data)                      # 转换为堆,最小的元素位于堆的根节点
heappush(data, -5)                 
[heappop(data) for i in range(3)] # 列表

十进制浮点运算

1.decimal 模块

用于十进制浮点运算

Decimal('1.00') % Decimal('.10') # Decimal('0.00')
1.00 % 0.10 # 0.09999999999999995
sum([Decimal('0.1')]*10) == Decimal('1.0') # True
0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 + 0.1 == 1.0 # False     0.1 的二进制表示为无限循环小数

标签:__,Python,Study,0.1,Part4,模块,print,import,self
From: https://blog.csdn.net/qq_24058289/article/details/141503952

相关文章

  • Python 3.11 从入门到实战1(环境准备)
            本篇文章是python3.11的学习开篇,我们的目标是:通过这一套资料学习下来,获得python基础学习与实例、实践相结合,使我们完全掌握python。并做到独立完成项目开发的能力。    今天的谈论的比较简单,也是后续学习的基础。python安装和工具pycharm的安装。pyth......
  • Python数据结构实战:列表、字典与集合的高效使用
    在日常的编程工作中,选择合适的数据结构对于提高程序效率至关重要。Python提供了丰富的内置数据结构,其中最常用的就是列表(List)、字典(Dictionary)和集合(Set)。本文将深入探讨这些数据结构,并介绍它们的内部实现以及如何高效地使用它们。1.列表(List)1.1定义与创建列表是......
  • Python数据结构精要:选择与应用
    数据结构是计算机科学中一个重要的概念,它涉及到如何组织和存储数据以便于高效地访问和修改。Python作为一种高级编程语言,提供了多种内置的数据结构来满足不同的需求。本文旨在介绍Python中常见的几种数据结构,并通过实例来说明它们的使用场景和优缺点。Python中的基本数......
  • Python——生成器、递归、内省、高阶和偏函数
    Python的生成器(Generators)是一种特殊的迭代器,它使用类似于函数的语法定义,但是使用yield语句一次返回一个值(可以多次返回),而不是使用return语句。生成器函数允许你声明一个像迭代器那样的对象,但是你可以使用更简洁的语法来创建它们。为什么要使用生成器?内存效率高:生成器按需产......
  • python基础学习总结(十)
    ​文章目录面向对象一.内置内属性二.对象销毁三.类的继承四.方法重写1.基础重载方法2.运算符重载3.类的属性和方法1.类的私有属性2.类的方法3.类的私有方法五.下划线说明面向对象一.内置内属性属性|定义----|----dict|类的属性(包含一个字典,由类......
  • Python实现局部线性嵌入(LLE)降维算法
    目录Python实现局部线性嵌入(LLE)降维算法的博客引言LLE算法原理1.确定邻域2.线性重构3.降维映射Python中的LLE实现1.创建LLE类2.实现瑞士卷数据集的LLE降维3.结果分析总结Python实现局部线性嵌入(LLE)降维算法的博客引言随着数据维度的增加,高维数据的分......
  • Python实现核主成分分析(KPCA)降维算法
    目录Python实现核主成分分析(KPCA)降维算法的博客引言KPCA算法原理1.核函数与核技巧2.中心化核矩阵3.特征分解Python中的KPCA实现1.创建KPCA类2.在瑞士卷数据集上应用KPCA3.结果分析总结Python实现核主成分分析(KPCA)降维算法的博客引言在高维数据分析中,主成......
  • python学习—redis入门,新手小白轻松学
    目录一.安装redis-py库二.连接redis服务器三.基本操作(1)字符串1.一次添加一个键值对2.一次添加多个键值对3.设置存在秒数4.设置过期时间(秒)5.设置存在天数 完整代码(2)列表1.添加数据2.从右侧删除数据3.从左侧删除数据4.获取列表的长度5.根据索引查找数......
  • 基于Python语言快速批量运行DSSAT模型及交叉融合、扩展
    随着数字农业和智慧农业的发展,基于过程的作物生长模型(Process-basedCropGrowthSimulationModel)在模拟作物对气候变化的响应与适应、农田管理优化、作物品种和株型筛选、农业碳中和、农田固碳减排等领域扮演着越来越重要的作用。DecisionSupportSystemsforAgrotechnolog......
  • 计算机毕业设计选题-基于python的医院预约挂号系统
    精彩专栏推荐订阅:在下方专栏......