我在python中有两个简短列表,我是一个初学者。如果有人可以协助我编写协程,通过一次打印一个项目来使我的列表交替出现,那将有很大帮助。
cars = ['BMW', 'Benz','Tesla']
veggies = ['Broccoli', 'Carrots', 'Spinach']
for item in cars:
print(item)
for item in veggies:
print(item)
答案 0 :(得分:2)
IIUC:
cars = ['BMW', 'Benz','Tesla']
veggies = ['Broccoli', 'Carrots', 'Spinach']
for i in zip(cars,veggies):
print('\n'.join(i))
或者:
cars = ['BMW', 'Benz','Tesla']
veggies = ['Broccoli', 'Carrots', 'Spinach']
for x,y in zip(cars,veggies):
print(x)
print(y)
两者都会交替显示两个列表
协程没有用,这里需要
如果列表的长度不同,请执行以下操作:
import itertools
for x,y in itertools.zip_longest(cars,veggies):
print(x)
print(y)