You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为Python列表设置文本索引?合并不同长度列表如何避免元素丢失?

问题1:用文件名作为索引替代数字索引

是的,你需要把列表转换成字典或DataFrame来实现文件名索引,两种方案各有适用场景:

方案1:使用字典(轻量高效)

直接将resumes定义为字典,以文件名作为键,对应文本内容作为值,修改代码如下:

import os
import docx2txt
import warnings
warnings.filterwarnings('ignore')

ext = ('.docx')
resume_path = 'C:\\Users\\resumes\\'

resumes = {}  # 改为字典
for files in os.listdir(resume_path):
    if files.endswith(ext):  # 过滤仅处理docx文件
        my_text = docx2txt.process(os.path.join(resume_path, files))
        resumes[files] = f"{files}----{my_text}--END_OF_RESUME--"
    print(len(resumes))

之后可直接通过文件名访问对应内容,例如resumes['aaron.docx']。

方案2:使用DataFrame(适合后续数据分析)

如果需要对内容做进一步数据处理,用pandas的DataFrame更方便,示例代码:

import os
import docx2txt
import pandas as pd
import warnings
warnings.filterwarnings('ignore')

ext = ('.docx')
resume_path = 'C:\\Users\\resumes\\'

filenames = []
contents = []
for files in os.listdir(resume_path):
    if files.endswith(ext):
        my_text = docx2txt.process(os.path.join(resume_path, files))
        filenames.append(files)
        contents.append(f"{files}----{my_text}--END_OF_RESUME--")

# 创建DataFrame并设置文件名为索引
resume_df = pd.DataFrame({'content': contents}, index=filenames)

之后可通过resume_df.loc['aaron.docx']获取对应行的内容。


问题2:合并长度不同的列表生成完整字典

zip()函数只会匹配到两个列表中最短的长度,因此会丢失长列表中超出的元素。解决方法是使用itertools.zip_longest(),它会以最长列表的长度为准,短列表元素不足时用指定值填充(默认是None)。

示例代码:

import itertools

# 假设list_a是5个元素的列表,list_b是3个元素的列表
list_a = ['aaron.docx', 'sam.docx', 'henry.docx', 'lisa.docx', 'john.docx']
list_b = ['content1', 'content2', 'content3']

# 用zip_longest生成完整字典,不足的位置补None
full_dict = dict(itertools.zip_longest(list_a, list_b))
# 结果:{'aaron.docx': 'content1', 'sam.docx': 'content2', 'henry.docx': 'content3', 'lisa.docx': None, 'john.docx': None}

# 也可以指定填充值,比如空字符串
full_dict = dict(itertools.zip_longest(list_a, list_b, fillvalue=''))
# 结果:{'aaron.docx': 'content1', 'sam.docx': 'content2', 'henry.docx': 'content3', 'lisa.docx': '', 'john.docx': ''}

内容的提问来源于stack exchange,提问作者ASH

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 14:03:18