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

BeautifulSoup.find_all结果append生成二维列表,如何获取一维列表

问题1:将二维嵌套列表转为一维列表

你得到嵌套列表的原因是re.findall()会返回所有匹配结果组成的列表,你的每个card-footer标签内只有一组数字,所以每次追加的都是单元素列表,最终形成二维结构,有两种常用解决方法:

  • 方法1:修改元素追加逻辑,直接取匹配到的第一个结果
import re
from bs4 import BeautifulSoup

stripped = []
prices = soup.find_all("div", class_="card-footer")
for p in prices:
    text = p.get_text(strip=True)
    nums = re.findall(r'\d+', text)
    # 先判断是否匹配到数字,避免空列表索引报错
    if nums:
        # 直接取第一个匹配的数字,不追加整个列表,需要整型可以套int()转换
        stripped.append(nums[0])
print(stripped)

运行后输出为一维列表:['555', '590', '599', '1000', '5000', '5000', '9999', '10000', '12000']

  • 方法2:对已生成的嵌套列表直接展平
    如果你已经得到了嵌套的二维列表,可以用列表推导式快速展平:
stripped = [['555'], ['590'], ['599'], ['1000'], ['5000'], ['5000'], ['9999'], ['10000'], ['12000']]
flat_stripped = [item for sublist in stripped for item in sublist]
print(flat_stripped)
问题2:更简便的数字提取方法

find_all()的作用是匹配符合规则的HTML标签,本身不具备文本内容过滤能力,无法在调用find_all()的同时直接提取数字,但可以简化后续处理逻辑,不需要调用re模块也能实现数字提取:
如果你的card-footer标签内只有一个数值,没有其他数字串,可以直接用str.isdigit()过滤字符拼接数字:

stripped = []
prices = soup.find_all("div", class_="card-footer")
for p in prices:
    text = p.get_text(strip=True)
    # 过滤所有数字字符后拼接
    num_str = ''.join([c for c in text if c.isdigit()])
    if num_str:
        stripped.append(num_str)

也可以直接写成一行列表推导式,代码更简洁:

# 一步提取所有数字,过滤空值后转整型
stripped = [int(''.join(c for c in p.get_text(strip=True) if c.isdigit())) for p in soup.find_all("div", class_="card-footer") if ''.join(c for c in p.get_text(strip=True) if c.isdigit())]

这种方法不需要引入re模块,代码更轻量。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 00:54:03