2015-10-18 47 views
-4
def insert(listA, listB, index): 
    for item in listA: 
     listB.append(item) 

    print(listB) 

此輸出列表幫助interration

>>> insert([1, 2, 3], ['a', 'b', 'c'], 2) 

>>> ['a', 'b', 'c', 1, 2, 3] 

如何使它輸出:[1, 2, 'a', 'b', 'c', 3]

+0

'listA [:index] + listB + listA [index:]' – inspectorG4dget

回答

0

listA的[指數:指數=數組listB

這將插入您的B名單列出A,在指數說明。

例如:

A = [1,2,3]

B = [4,5,6]

一個[2:2] = B

一個是現在[1,2,4,5,6,3]

0

的一種方法是通過根據index切片listA構建一個新的列表:

def insert(listA, listB, index): 
    return listA[0:index] + listB + listA[index:] 

(請注意,此實現排除任何參數驗證,爲bravity的緣故)