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

如何以最优方式打印嵌套列表(list of lists)中的元素?

嘿,这个需求很实用,我来给你几个通用的解决方案,完全不用硬编码索引,不管你的嵌套列表里有多少个子列表都能搞定~

最简洁的方案:用zip()函数

zip()天生就是用来处理这种按列遍历的场景,它会把多个可迭代对象按位置配对。我们只需要把嵌套列表解包后传给zip(),就能拿到每一列的元素组合,接着逐个打印就行:

l1 = [['hello', 'world', 'bye'], ['name', 'tour', 'now']]
# 解包嵌套列表,按列分组
for column in zip(*l1):
    # 遍历每一列的元素,用end=' '保持在同一行输出
    for item in column:
        print(item, end=' ')

运行这段代码就会输出:hello name world tour bye now

兼容不同长度子列表的扩展方案

如果你的嵌套列表里子列表长度不一样(比如有的子列表更长),可以用itertools.zip_longest来处理,它会用指定的填充值补全短的子列表:

from itertools import zip_longest

l1 = [['hello', 'world', 'bye'], ['name', 'tour', 'now', 'extra']]
# fillvalue用来填充短子列表的空缺位置,这里设为空字符串
for column in zip_longest(*l1, fillvalue=''):
    for item in column:
        if item:  # 跳过空的填充值
            print(item, end=' ')

输出结果:hello name world tour bye now extra

用while循环实现通用版本

如果你还是想用while循环的方式,也可以改成通用版,不用硬编码子列表的索引:

l1 = [['hello', 'world', 'bye'], ['name', 'tour', 'now']]
# 获取子列表的总数
sublist_num = len(l1)
# 找到最长子列表的长度,避免索引越界
max_len = max(len(sublist) for sublist in l1)

i = 0
while i < max_len:
    # 遍历每个子列表,取出第i个元素
    for sublist in l1:
        if i < len(sublist):  # 确保子列表有足够的长度
            print(sublist[i], end=' ')
    i += 1

这个版本不管你嵌套列表里有2个还是10个子列表,都能正常按列遍历打印。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 04:27:42