如何在Python中按索引配对打印数组元素?
按索引配对打印两个列表元素的解决方案
要实现两个列表按索引对应配对打印,最简洁且Pythonic的方式是使用zip()函数,它会自动将多个可迭代对象中相同索引的元素打包成元组,完全匹配你的需求。
修改后的核心代码
bright_fruit = ['banana','orange','mango'] red_fruit = ['tomato','grape','apple'] for x, y in zip(bright_fruit, red_fruit): print(x, y)
运行这段代码后,会直接输出你期望的结果:
banana tomato
orange grape
mango apple
复杂场景的扩展处理
如果后续你的两个列表长度不一致,zip()会以较短的列表长度为准停止循环。如果需要保留所有元素,对缺失的部分用默认值填充,可以使用itertools模块中的zip_longest:
from itertools import zip_longest bright_fruit = ['banana','orange','mango', 'pineapple'] red_fruit = ['tomato','grape','apple'] # 用自定义内容填充缺失的元素,这里用'无对应元素',也可以用None或其他值 for x, y in zip_longest(bright_fruit, red_fruit, fillvalue='无对应元素'): print(x, y)
基于索引循环的替代方案
如果你想更直观地理解索引对应的逻辑,也可以通过range()和列表索引来实现:
bright_fruit = ['banana','orange','mango'] red_fruit = ['tomato','grape','apple'] # 确保两个列表长度相同,否则会引发索引越界错误 for i in range(len(bright_fruit)): print(bright_fruit[i], red_fruit[i])
内容的提问来源于stack exchange,提问作者Uchsun
相关产品推荐
相关产品推荐

