2011-02-04 127 views
2

我有2所列出:如何打印2個列表循環?

filtered_items_list = [src1, scr2, scr3] 
filtered_items_url_list = [url1, url2, url3] 

我需要打印的

src1, url1 
src2, url2 
src3, url3 

如果我嘗試:

>>> for src, url in filtered_items_list, filtered_items_url_list: 
    print src, url 

我得到這個錯誤:

ValueError: too many values to unpack 

如果我嘗試這樣的:

>>> for src in filtered_items_list: 
     for url in filtered_items_url_list: 
      print """"src: %s; url: %s""" % (src, url) 

我得到這個:

"src: src1; url: url1 
"src: src1; url: url2 
"src: src1; url: url3 
"src: scr2; url: url1 
"src: scr2; url: url2 
"src: scr2; url: url3 
"src: scr3; url: url1 
"src: scr3; url: url2 
"src: scr3; url: url3 
>>> 

您能否提供一個解決方案嗎?謝謝!

回答

8

你應該使用zip()

for src, url in zip(filtered_items_list, filtered_items_url_list): 
    print src, url 
+5

[izip(http://docs.python.org/library/itertools.html#itertools.izip)往往BA更好的選擇,因爲它避免了不必要的複製名單。請注意,它們都在最短列表的末尾處被切斷。如果你想使用最長的`izip_longest()`,它會爲剩餘的填充None(或其他默認值)。 – chmullig 2011-02-04 17:53:04