如何以循环顺序访问两个列表中的项目?

时间:2016-10-04 20:45:22

标签: python list

我有2个清单,

list_a = ['color-1', 'color-2', 'color-3', 'color-4']
list_b = ['car1', 'car2', 'car3', 'car4' ........... 'car1000']

我需要以list_a

的循环顺序访问元素
['color-1']['car1']
['color-2']['car2']
['color-3']['car3']
['color-4']['car4']
['color-1']['car5']  #list_a is starting from color-1 once it reaches end
['color-2']['car6']  #... goes on until end of items in list_b

我试过这个,它不起作用。请指教。

start=0
i=0
for car_idx in xrange(start, end):
    if i <= len(color_names):
        try:
            self.design(color_names[i], self.cars[car_idx])
            i+=1
        except SomeException as exe:
            print 'caught an error'

2 个答案:

答案 0 :(得分:6)

使用itertools.cyclelist_a开始循环迭代。 使用zip将循环迭代中的项与list_b中的项配对。当传递给zip(即zip)的最短迭代结束时,list_b返回的可迭代将停止。

import itertools as IT
list_a = ['color-1', 'color-2', 'color-3', 'color-4']
list_b = ['car1', 'car2', 'car3', 'car4', 'car5', 'car6', 'car1000']

for a, b in zip(IT.cycle(list_a), list_b):
    print(a, b)

打印

color-1 car1
color-2 car2
color-3 car3
color-4 car4
color-1 car5
color-2 car6
color-3 car1000

答案 1 :(得分:2)

使用模运算符%索引到适当的范围:

len_a = len(list_a)
len_b = len(list_b)
end = max(len_a, len_b)
for i in range(end):
    print(list_a[i % len_a], list_b[i % len_b])
    # ... do something else