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

如何从Python列表的'time=数字'字符串中提取数字?

提取列表中字符串的纯数字部分

针对给定的列表,这里提供几种简单直接的方法提取数字并转换为整数类型:

方法1:使用split()分割字符串

每个元素都是time=数字的格式,用=分割后取第二部分即可:

time_list = ['time=139', 'time=102', 'time=120', 'time=105', 'time=116', 'time=183', 'time=153', 'time=100', 'time=151', 'time=123', 'time=155', 'time=135']
numbers = [int(item.split('=')[1]) for item in time_list]
print(numbers)
# 输出: [139, 102, 120, 105, 116, 183, 153, 100, 151, 123, 155, 135]

方法2:固定位置切片

由于time=是固定的5个字符长度,直接从第5位开始截取字符串:

time_list = ['time=139', 'time=102', 'time=120', 'time=105', 'time=116', 'time=183', 'time=153', 'time=100', 'time=151', 'time=123', 'time=155', 'time=135']
numbers = [int(item[5:]) for item in time_list]
print(numbers)
# 输出: [139, 102, 120, 105, 116, 183, 153, 100, 151, 123, 155, 135]

方法3:正则表达式(适配复杂格式)

如果后续字符串格式可能变化,用正则匹配连续数字更灵活:

import re

time_list = ['time=139', 'time=102', 'time=120', 'time=105', 'time=116', 'time=183', 'time=153', 'time=100', 'time=151', 'time=123', 'time=155', 'time=135']
numbers = [int(re.search(r'\d+', item).group()) for item in time_list]
print(numbers)
# 输出: [139, 102, 120, 105, 116, 183, 153, 100, 151, 123, 155, 135]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 04:02:59