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

Python使用append生成嵌套列表及路径格式混合问题求助

解决列表扁平化与跨平台路径兼容问题

用户原代码:

imageExtensionList = ['jpg', '.arw', '.tif', 'mp4']
fileList = []
for extension in imageExtensionList:
    searchStr = str(importPath) + '/**/*.' + extension
    files = glob.glob(searchStr, recursive=True)
    fileList.append(files)

一、将嵌套列表转为一维列表

有两种思路,推荐从源头避免嵌套:

  • 直接生成一维列表:把fileList.append(files)替换成fileList.extend(files)。glob.glob返回的是文件路径列表,extend会把列表中的每个路径直接追加到fileList,而非把整个列表作为单个元素加入,一步到位得到一维列表。
  • 事后扁平化嵌套列表:如果已经生成了嵌套列表,可用以下方法处理:
    • 列表推导式:flat_fileList = [file for sublist in fileList for file in sublist]
    • itertools.chain工具:
      import itertools
      flat_fileList = list(itertools.chain.from_iterable(fileList))
      

二、修正跨平台路径格式问题

不要手动拼接路径字符串,用Python标准库自动适配系统路径分隔符:

方案1:使用pathlib(推荐,Python 3.4+)

pathlib是面向对象的路径处理库,自动兼容Windows/Unix路径:

from pathlib import Path

imageExtensionList = ['jpg', 'arw', 'tif', 'mp4']  # 统一去掉前缀点,后续拼接时添加
fileList = []
import_path = Path(importPath)  # 将输入路径转为Path对象

for extension in imageExtensionList:
    # rglob递归查找所有匹配后缀的文件,返回Path对象迭代器
    files = [str(file) for file in import_path.rglob(f"*.{extension}")]
    fileList.extend(files)

方案2:使用os.path

传统路径处理模块,同样能自动生成符合系统规范的路径:

import os
import glob

imageExtensionList = ['jpg', 'arw', 'tif', 'mp4']
fileList = []

for extension in imageExtensionList:
    # os.path.join自动用系统分隔符拼接路径
    search_str = os.path.join(importPath, '**', f'*.{extension}')
    files = glob.glob(search_str, recursive=True)
    fileList.extend(files)

注意:原代码中imageExtensionList里的后缀有的带点(.arw)有的不带(jpg),统一格式可以避免重复匹配或漏匹配,建议统一去掉前缀点,后续拼接时统一添加*.。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 06:55:19