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

如何在Python中转置字符串列表并生成整数子列表

实现方法

你可以通过两层循环来实现需求:外层循环遍历字符的位置索引(0到8,共9个位置),内层循环遍历原列表的每个字符串,提取对应位置的字符并转换为整数,最终将这些整数组成子列表,收集到结果中。

基础循环写法

original_list = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']

result = []
# 遍历每个位置索引(0到8)
for pos in range(9):
    sub_list = []
    # 遍历原列表的每个字符串
    for s in original_list:
        # 提取对应位置字符并转成整数,加入子列表
        sub_list.append(int(s[pos]))
    result.append(sub_list)

# 验证前两个子列表
print(result[0])  # 输出: [1, 2, 3, 4, 5, 6, 7, 8, 9]
print(result[1])  # 输出: [2, 3, 4, 5, 6, 7, 8, 9, 1]

简洁列表推导式写法

如果想要更紧凑的代码,可以用嵌套列表推导式,逻辑和上面完全一致:

original_list = ['123456789', '234567891', '345678912', '456789123', '567891234', '789123456', '891234567', '912345678']

result = [[int(s[pos]) for s in original_list] for pos in range(9)]

# 验证输出
print(result[0])
print(result[1])

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 20:31:34