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

Python拆分含空格分隔值的列表元素并合并为一维数值列表

错误原因
  • split()是Python字符串类型的专属方法,你调用该方法的myvalues是列表类型,列表本身没有split属性,因此抛出AttributeError。
解决方法

你的原始列表结构如下:

myvalues = ['20 32 35 47 64', '15 17 25 32 53', '07 10 12 61 65', '08 14 31 58 68', '01 10 44 47 56']

方案1:列表推导式(最简洁,推荐普通场景使用)

如果需要最终元素为整数类型,直接用以下代码:

myvallist = [int(num) for item in myvalues for num in item.split()]

如果需要保留字符串格式的前导零(例如保留'07'而不是转为7),去掉int()转换即可:

myvallist = [num for item in myvalues for num in item.split()]

方案2:itertools链式拼接(适合大数据量场景,性能更高)

from itertools import chain
myvallist = list(map(int, chain.from_iterable(item.split() for item in myvalues)))

两种方案最终输出的整数格式结果都符合要求:
[20, 32, 35, 47, 64, 15, 17, 25, 32, 53, 7, 10, 12, 61, 65, 8, 14, 31, 58, 68, 1, 10, 44, 47, 56]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 13:21:00