Python中如何遍历两个不等长列表并按要求输出全部元素?
解决不等长列表的对应输出问题
针对你的需求,有两种简单的实现方式:
方法一:使用标准库itertools.zip_longest
zip_longest会遍历到最长列表的末尾,短列表的空缺位置默认用None填充,我们只需要在输出时跳过None即可:
from itertools import zip_longest list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] list2 = [20, 21, 22, 23, 24, 25, 26, 27] for a, b in zip_longest(list1, list2): items = [] if a is not None: items.append(str(a)) if b is not None: items.append(str(b)) print(' '.join(items))
方法二:手动遍历索引(更直观,适合新手理解)
先获取两个列表的最大长度,然后逐个索引取值,存在就输出,不存在就忽略:
list1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] list2 = [20, 21, 22, 23, 24, 25, 26, 27] max_len = max(len(list1), len(list2)) for i in range(max_len): num1 = str(list1[i]) if i < len(list1) else '' num2 = str(list2[i]) if i < len(list2) else '' print(f"{num1} {num2}".strip())
两种方法都能输出你想要的结果,第一种用标准库更简洁,第二种手动操作更清晰,适合新手理解底层逻辑。
内容的提问来源于stack exchange,提问作者user19092610
相关产品推荐
相关产品推荐

