2015-12-02 182 views
-2

如何添加一個列表到另一個列表中,我繼續遇到我的for循環遍歷整個列表中的第二個列表的問題。for循環內另一個for循環Python

如果aList[1, 2, 3, 4],我想輸出1hello, 2good, 3what...等。

def function(aList): 
    myList = ['hello','good','what','tree'] 
    newList = [] 

    for element in aList: 
     for n in myList: 
       newList.append[element+n] 

輸入:

[1, 2, 3, 4] 

預期輸出:

['1hello', '2good', '3what', '4tree'] 
+1

那麼你想得到什麼? –

+0

你確定你不想'首先在myList'中爲''zip''n? –

+0

我想他想要'[a [0],b [0],a [1],b [1] ..]'等 – Dleep

回答

1

你想zip

def function(aList): 
    myList = ['hello', 'good', 'what', 'tree'] 
    return [str(a) + b for a, b in zip(aList, myList)] 

輸出:

In [4]: function([1, 2, 3, 4]) 
Out[4]: ['1hello', '2good', '3what', '4tree'] 

您還需要投在價值傳遞給一個字符串,以確保您可以連接到串在你myList

+0

正是我在找的,謝謝! –

+1

@kevin Guan,謝謝,你打敗了我 –

1

閱讀List Comprehensions

aList = ['1', '2', '3'] 
print [element + n for element in aList for n in myList] 
['1hello', '1good', '1what', '1tree', '2hello', '2good', '2what', '2tree', '3hello', '3good', '3what', '3tree'] 

zip

aList = ['1', '2', '3'] 
print [element + n for element, n in zip(aList, myList)] 
['1hello', '2good', '3what'] 
+0

是的,因爲我試圖猜測你需要什麼。 –

+1

對不起,我改進了答案。 –

2

在你的問題,我覺得沒有必要添加兩個for循環。一個循環本身就夠了。

讓我舉兩個例子,哪一個符合你的需要就用那個。

案例1: - 一個for循環

aList = [1,2,3,4] 
def function(aList): 
    myList = ['hello','good','what','tree'] 
    newList = [] 

    for i in range(len(aList)): 
     newList.append(str(aList[i]) + myList [i]) 

    return newList 

這將返回1hello , 2good ...

案例2: - 有兩個for循環

aList = [1,2,3,4] 
def function(aList): 
    myList = ['hello','good','what','tree'] 
    newList = [] 

    for element in aList: 
     for i in range(len(myList)): 
     newList.append(str(element) + myList [i]) 

    return newList 

這將返回1hello , 1good ... 2hello, 2good

我希望這會有所幫助...