2016-10-04 74 views
0

我有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

使用模運算符%索引到合適的範圍:

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 
+0

這是因爲它是如何不可知的,其名單是最短的不錯。 –

6

使用itertools.cycle使循環迭代出來的list_a。 使用zip將來自循環迭代的項目與來自list_b的項目配對。當zip(即list_b)中的最短迭代結束時,由zip返回的迭代將停止。

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 
+0

你打敗了我! –

相關問題