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

如何修正Python代码实现从字符串列表提取连续数字与字符串

解决方案

要实现从OGList中提取连续数字序列和忽略空格的连续字母序列,核心是把同类型的连续字符拼接成完整序列,而不是逐个拆分。用正则表达式可以高效解决这个问题,具体代码如下:

示例代码

import re

# 假设你的原始列表是这样(可根据实际情况替换)
OGList = ['A 10', 'BMW i 320', 'Nissan NSX 200', 'Benz c 220']

# 提取连续数字序列
numlist = [re.findall(r'\d+', item)[0] for item in OGList]
# 提取忽略空格的连续字母序列
strlist = [''.join(re.findall(r'[a-zA-Z]', item)) for item in OGList]

print(numlist)  # 输出: ['10', '320', '200', '220']
print(strlist)  # 输出: ['A', 'BMWi', 'NissanNSX', 'Benzc']

代码说明

  • 提取数字:re.findall(r'\d+', item)会匹配当前字符串中所有连续的数字序列(\d+表示1个或多个数字),因为每个列表元素里只有一组数字,所以取索引[0]即可。
  • 提取字母:re.findall(r'[a-zA-Z]', item)会把当前字符串中所有字母(大小写都匹配)单独提取出来,用''.join()拼接后就自动忽略了原字符串中的空格,得到连续的字母序列。

适配更复杂场景的写法

如果OGList的元素中可能包含多组数字或字母序列,比如['A 10 20', 'BMW i 320'],可以改用循环遍历收集结果:

numlist = []
strlist = []

for item in OGList:
    # 收集所有连续数字序列
    numlist.extend(re.findall(r'\d+', item))
    # 收集忽略空格的连续字母序列(按连续块拆分)
    no_space_item = item.replace(' ', '')
    strlist.extend(re.findall(r'[a-zA-Z]+', no_space_item))

内容的提问来源于stack exchange,提问作者Arnu C.

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.11 13:16:18