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

如何将正则表达式生成的嵌套子列表合并为单个列表?

解决嵌套列表扁平化问题

你当前的代码通过append()将每行提取到的数字子列表添加到主列表,导致生成嵌套结构。要得到单个扁平列表,有以下几种直接的解决方式:

方法1:直接用extend()替代append()

在遍历每行提取数字时,使用extend()可以将子列表中的元素逐个添加到主列表,而不是把整个子列表作为元素插入:

import re  # 原代码缺少re模块导入,必须补上

fname = input('Enter file name:')
if len(fname) < 1:
    fname = 'regex_sum_42.txt'
fhand = open(fname)
numlist = list()
for line in fhand:
    line.rstrip()
    numl = re.findall('([0-9]+)', line)
    if len(numl) < 1:
        continue
    numlist.extend(numl)  # 替换append为extend
# 可选:将字符串数字转为整数
numlist = [int(num) for num in numlist]
print(numlist)

方法2:扁平化已生成的嵌套列表

如果已经得到了嵌套列表(比如原代码输出的numlist),可以用列表推导式快速扁平化:

# 假设已有的嵌套列表是nested_list
nested_list = [['1','2','3'],['4','5']]
flat_list = [int(num) for sublist in nested_list for num in sublist]
print(flat_list)  # 输出 [1,2,3,4,5]

方法3:使用itertools.chain(适合大型列表)

对于数据量较大的嵌套列表,用itertools.chain效率更高:

import itertools

nested_list = [['1','2','3'],['4','5']]
flat_list = list(itertools.chain.from_iterable(nested_list))
flat_list = [int(num) for num in flat_list]
print(flat_list)

注意点

  • 原代码缺少import re语句,运行会报错,必须添加。
  • re.findall()返回的是字符串类型的数字,若需要整数类型,记得做类型转换。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:50:24