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

Python中如何从BeautifulSoup爬取的列表中筛选所有小于50的数值

筛选列表中数值小于50的元素的实现方法

你当前拿到的records列表元素都是字符串格式,部分数值还带千位分隔符逗号,无法直接做数值比较,需要先做格式转换再筛选,以下是两种常用实现方案:


方式1:列表推导式(代码最简洁)

# 保留原字符串格式的筛选结果
filtered_records = [item for item in records if int(item.replace(',', '')) < 50]

# 如果要直接得到整数格式的结果,替换为下面的写法
# filtered_records = [int(item.replace(',', '')) for item in records if int(item.replace(',', '')) < 50]

逻辑说明:

  • 先用replace(',', '')移除字符串里的千位分隔符逗号
  • 再用int()将处理后的字符串转成整数
  • 最后判断数值是否小于50,符合条件的元素会被保留到新列表中

方式2:普通for循环(逻辑更清晰,适合新手理解)

filtered_records = []
for item in records:
    # 处理字符串格式,转换为整数
    num_value = int(item.replace(',', ''))
    if num_value < 50:
        # 要保留原字符串就写filtered_records.append(item)
        # 要存储数值就写filtered_records.append(num_value)
        filtered_records.append(item)

print(filtered_records)

可选:异常兼容方案

如果后续爬取的内容可能出现非数字字符,可以加异常捕获避免程序报错:

filtered_records = []
for item in records:
    try:
        num_value = int(item.replace(',', ''))
        if num_value < 50:
            filtered_records.append(item)
    except ValueError:
        # 非数字格式的元素直接跳过
        continue

运行结果

用你给出的records列表运行后,得到的筛选结果为:

['17', '32', '28', '32', '25', '27', '30', '30', '32', '17', '7', '25', '11', '20', '7', '11', '9', '14', '6', '9', '0']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.02 22:09:04