2017-06-07 28 views
1

在我的Python代碼,我有2所列出Python的清單2只列出了子彈形

myList = ["Example", "Example2", "Example3"] 
mySecondList = ["0000", "1111", "2222"] 

我需要打印這些讓他們看起來像這樣:

- Example 0000 
- Example2 1111 
- Example3 2222 

有什麼辦法來實現這個?

+0

是的,有很多方法。你有嘗試過嗎? – SiHa

回答

5

是的,找zip

myList = ["Example", "Example2", "Example3"] 
mySecondList = ["0000", "1111", "2222"] 

for a, b in zip(myList, mySecondList): 
    print("- {} {}".format(a, b)) 
- Example 0000 
- Example2 1111 
- Example3 2222 

以上會工作,如果列表具有相同的大小,否則你應該根據調查izip_longestzip_longestitertools模塊在您使用的蟒蛇版本

0

我會推薦使用zip()zip_longest()爲您的問題。

但是,不使用任何built-in模塊/功能。您可以創建自己的'哈克'方法,您自己的方法非常類似於zip()函數。

下面是一個例子:

def custom_zip(a, b, fill=None): 
    length = max(len(a), len(b)) 
    for k in range(length): 
     if k > len(a): 
      yield fill, b[k] 
     elif k > len(b): 
      yield a[k], fill 
     else: 
      yield a[k], b[k] 

a = ["Example", "Example2", "Example3"] 
b = ["0000", "1111", "2222"] 

for k, v in custom_zip(a,b): 
    print("- {} {}".format(k, v)) 

輸出:

- Example 0000 
- Example2 1111 
- Example3 2222 

此外,您還可以看看的zip()official documentation相當。