Python在不同对象中使用 in 操作符的查找效率

在Python中 in 操作符可以用于判断某个元素是否存在于当前对象中,而对于不同的Python对象,使用 in 操作符的处理效率是不一样的。

今天我们主要针对 4 种不同的Python数据类型进行学习:list列表、tuple元组、set集合、dict字典。

测试过程

我们用于测试的 4 种Python数据类型,分别为 tmp_list 、tmp_tuple、tmp_set、tmp_dict,测试过程中,它们所包含的元素都是相同的,均通过 random.randint(0, num) 随机生成,但它们的长度均为 num - 3 ,也就是说在 [0, num] 范围内,将有3个整数不在上面的对象中,我们需要把这3个整数找出来。

测试代码如下:

import time
import random


def demo(target, num):
    time1 = time.time()
    res = []
    for i in range(num):
        if i not in target:
            res.append(i)
    time2 = time.time()
    print("结果:{},当前类型:{},耗时:{}".format(res, type(target), time2 - time1))

#学习中遇到问题没人解答?小编创建了一个Python学习交流群:531509025

num = 500
tmp_set = set()
while len(tmp_set) <= num - 3:
    tmp_set.add(random.randint(0, num))
tmp_list = list(tmp_set)
tmp_tuple = tuple(tmp_set)
tmp_dict = {key: "" for key in tmp_set}

demo(tmp_list, num)
demo(tmp_tuple, num)
demo(tmp_set, num)
demo(tmp_dict, num)

当 num = 50 时,得到如下结果:

不包含的整数:[25, 31, 36],当前类型:<class 'list'>,耗时:0.0
不包含的整数:[25, 31, 36],当前类型:<class 'tuple'>,耗时:0.0
不包含的整数:[25, 31, 36],当前类型:<class 'set'>,耗时:0.0
不包含的整数:[25, 31, 36],当前类型:<class 'dict'>,耗时:0.0

当 num = 500 时,得到如下结果:

不包含的整数:[114, 329, 355],当前类型:<class 'list'>,耗时:0.0059354305267333984
不包含的整数:[114, 329, 355],当前类型:<class 'tuple'>,耗时:0.0052182674407958984
不包含的整数:[114, 329, 355],当前类型:<class 'set'>,耗时:0.0
不包含的整数:[114, 329, 355],当前类型:<class 'dict'>,耗时:0.0

当 num = 5000 时,得到如下结果:

不包含的整数:[445, 850, 3547],当前类型:<class 'list'>,耗时:0.3342933654785156
不包含的整数:[445, 850, 3547],当前类型:<class 'tuple'>,耗时:0.39918947219848633
不包含的整数:[445, 850, 3547],当前类型:<class 'set'>,耗时:0.00099945068359375
不包含的整数:[445, 850, 3547],当前类型:<class 'dict'>,耗时:0.0

当 num = 50000 时,得到如下结果:

不包含的整数:[9296, 18652, 32281],当前类型:<class 'list'>,耗时:26.92029118537903
不包含的整数:[9296, 18652, 32281],当前类型:<class 'tuple'>,耗时:25.956974506378174
不包含的整数:[9296, 18652, 32281],当前类型:<class 'set'>,耗时:0.009968996047973633
不包含的整数:[9296, 18652, 32281],当前类型:<class 'dict'>,耗时:0.009973287582397461

当 num = 55000 时,得到如下结果:

不包含的整数:[16086, 33891, 46161],当前类型:<class 'list'>,耗时:52.91718029975891
不包含的整数:[16086, 33891, 46161],当前类型:<class 'tuple'>,耗时:52.84810948371887
不包含的整数:[16086, 33891, 46161],当前类型:<class 'set'>,耗时:0.009554624557495117
不包含的整数:[16086, 33891, 46161],当前类型:<class 'dict'>,耗时:0.007979393005371094

当 num = 75000 时,得到如下结果:

不包含的整数:[23057, 35827, 69232],当前类型:<class 'list'>,耗时:75.57932734489441
不包含的整数:[23057, 35827, 69232],当前类型:<class 'tuple'>,耗时:64.49729013442993
不包含的整数:[23057, 35827, 69232],当前类型:<class 'set'>,耗时:0.005983591079711914
不包含的整数:[23057, 35827, 69232],当前类型:<class 'dict'>,耗时:0.005979776382446289

当 num = 100000 时,得到如下结果:

不包含的整数:[22499, 22800, 29652],当前类型:<class 'list'>,耗时:110.19707798957825
不包含的整数:[22499, 22800, 29652],当前类型:<class 'tuple'>,耗时:109.08251285552979
不包含的整数:[22499, 22800, 29652],当前类型:<class 'set'>,耗时:0.011965036392211914
不包含的整数:[22499, 22800, 29652],当前类型:<class 'dict'>,耗时:0.009937524795532227

结论

通过上面的测试,我们可以看到,总体来说,list、tuple它们使用 in 操作符的查找效率相差不多,set、dict它们使用 in 操作符的查找效率相差不多,但随着查找数据量的增大,list、tuple的处理效率变得越来越慢,而set、dict的处理效率,将远远优于list及tuple。

list列表、tuple元组、set集合、dict字典,使用 in 操作符查找的平均时间复杂度如下:

数据类型使用 in 操作符查找的平均时间复杂度
listO(n)
tupleO(n)
setO(1)
dIctO(1)
<think>我们之前讨论了合并Word文档,现在用户的新问题是:使用Python删除Word中的分页符。 用户参考了一个关于jieba分词的引用,但这与当前问题无关,因此忽略该引用。 删除Word文档中的分页符有两种主要方法: 1. 使用win32com(依赖Microsoft Word) 2. 使用python-docx(纯Python,但不支持直接删除分页符,需要操作底层XML) 由于用户之前使用了win32com,这里优先提供win32com方案,因为它在格式处理上更直接。同时,我们也会提供python-docx的方案(需要操作XML,较为复杂)。 注意:分页符在Word中有多种形式,常见的有: - 手动插入的分页符(Ctrl+Enter) - 由段落格式设置的分页(如段前分页、段中分页等) 我们这里主要处理手动插入的分页符(即`wdPageBreak`类型的分页符)。 方法一:使用win32com 在Word VBA中,分页符对应的对象是`Break`,其类型为`wdPageBreak`(枚举值为7)。我们可以遍历文档中的所有段落,查找分页符并删除。 方法二:使用python-docx 由于python-docx没有直接提供删除分页符的API,我们需要操作底层XML。在.docx文件中,分页符对应的XML元素是`<w:br w:type="page"/>`。我们可以遍历所有段落中的run,查找该元素并删除。 但请注意,使用python-docx处理分页符可能会破坏原有格式,因为分页符可能与其他格式标记混合存在。因此,我们更推荐win32com方案。 下面给出两种方案的代码: 方案1:win32com(Windows + Office环境) </think>### 使用Python删除Word文档分页符的方法 以下是两种高效删除Word文档分页符的方案,根据使用场景选择: --- #### 方法1:使用python-docx库(推荐方案) ```python from docx import Document from docx.enum.text import WD_BREAK def remove_page_breaks(input_path, output_path): """删除文档中所有分页符""" doc = Document(input_path) # 遍历所有段落 for para in doc.paragraphs: runs_to_remove = [] # 检查每个run中的分页符 for run in para.runs: # 查找分页符并标记待删除 if WD_BREAK.PAGE in run._element.xml: runs_to_remove.append(run) # 删除包含分页符的run for run in runs_to_remove: run.clear() # 清空run内容 # 保存处理后的文档 doc.save(output_path) print(f"✅ 已删除分页符并保存到: {output_path}") # 使用示例 remove_page_breaks("原始文档.docx", "处理后文档.docx") ``` **技术说明**: - 通过解析XML结构精准定位分页符元素`<w:br w:type="page"/>`[^5] - 使用`run.clear()`保留段落格式的同时删除分页符 - 依赖库:`pip install python-docx` - 适用于所有平台(Windows/Linux/Mac) --- #### 方法2:使用win32com(Windows专用) ```python import win32com.client as win32 def remove_page_breaks_win32(input_path, output_path): """Windows环境下删除分页符""" word = win32.Dispatch("Word.Application") try: word.Visible = False doc = word.Documents.Open(os.path.abspath(input_path)) # 创建查找对象 finder = word.Selection.Find finder.ClearFormatting() finder.Replacement.ClearFormatting() # 设置查找内容为手动分页符 finder.Text = "^m" # Word特殊代码^m表示分页符 finder.Replacement.Text = "" # 替换为空 # 执行全文档替换 finder.Execute(Replace=2) # 2=wdReplaceAll doc.SaveAs(os.path.abspath(output_path)) print(f"✅ 已删除分页符并保存到: {output_path}") finally: doc.Close() word.Quit() ``` **技术说明**: - 使用Word内置查找替换功能(`^m`表示分页符)[^6] - 依赖Office环境,仅Windows可用 - 需安装依赖:`pip install pywin32` --- ### 分页符删除效果对比 | 方案 | 平台兼容性 | 格式保留 | 复杂分页处理 | |------|------------|----------|--------------| | python-docx | 全平台 | 精确保留 | 支持复杂布局 | | win32com | 仅Windows | 良好保留 | 依赖Office引擎 | $$ \text{处理效率} = \begin{cases} \text{python-docx} & \text{直接操作XML} \\ \text{win32com} & \text{通过COM接口} \end{cases} $$ ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值