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

Python中如何将交替元素列表转换为嵌套子列表

问题:将交替排列的字符串+数值列表转换为嵌套列表

现有一个Python列表,元素按字符串+数值的规律交替排列,字符串内容、数值大小及整体组数均为随机值,示例如下:

values = ['random word1', 20, 'random word2', 54…]

需要将其转换为每组包含一个字符串和对应数值的嵌套列表,示例如下:

values = [['random word1', 20], ['random word2', 54]…]

方法一:切片+zip配对

利用Python切片特性分离字符串和数值,再用zip一一配对:

values = ['random word1', 20, 'random word2', 54, 'random word3', 78]
# 先配对成元组,再转成嵌套列表
result = [list(pair) for pair in zip(values[::2], values[1::2])]
print(result)
# 输出:[['random word1', 20], ['random word2', 54], ['random word3', 78]]
  • 说明:values[::2]提取所有偶数索引的字符串元素,values[1::2]提取所有奇数索引的数值元素,zip将两组元素按顺序配对,最后转成嵌套列表。

方法二:循环步长遍历

通过步长为2的循环,每次取相邻的字符串和数值组成子列表:

values = ['random word1', 20, 'random word2', 54, 'random word3', 78]
result = []
for i in range(0, len(values), 2):
    result.append([values[i], values[i+1]])
print(result)
# 输出:[['random word1', 20], ['random word2', 54], ['random word3', 78]]
  • 说明:range(0, len(values), 2)生成从0开始、步长为2的索引序列,每次循环取当前索引和下一个索引的元素组成子列表。

方法三:迭代器配对(适合大列表)

用迭代器避免生成切片副本,节省内存:

values = ['random word1', 20, 'random word2', 54, 'random word3', 78]
it = iter(values)
result = [list(pair) for pair in zip(it, it)]
print(result)
  • 说明:将列表转为迭代器后,zip(it, it)会每次从迭代器中取出两个元素配对,无需额外存储切片数据,适合处理大规模列表。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 00:55:14