2016-11-15 152 views
0

比如我想list1的是我不能顯示列表正確

['abc', '123', 'def', '456', 'ghi', '789'] 

和列表2

[['abc', '123'], ['def', '456'], ['ghi', '789']] 

但是它打印

['ghi', '789'] 

[['abc', '123'], ['def', '456'], ['ghi', '789']] 

And if I put outside the range it prints 

['abc', '123', 'def', '456', 'ghi', '789'] 

[['abc', '123', 'def', '456', 'ghi', '789'], ['abc', '123', 'def', '456', 'ghi', '789'], ['abc', '123', 'def', '456', 'ghi', '789']] 

爲什麼它會覆蓋前兩個元素?

回答

0

我認爲這是因爲list1在循環內部並且在每次迭代時被設置爲null。

我嘗試這樣做,它產生你正在尋找的結果:

list2 = [] 

q = int(input('How many contacts would you like to add?: ')) 
list1 = [] 
    for i in range(q): 
    tempList= [] 
    name = input('Name: ') 
    number = input('Number: ') 
    tempList.append(name) 
    tempList.append(number) 
    list1.append(name) 
    list1.append(number) 
    list2.append(tempList) 

print(list1) 
print(list2) 

輸出:

[ 'ABC', '123', '高清', '456',' GHI」, '789']

[[ 'ABC', '123'],[ '高清', '456'],[ 'GHI', '789']]

1

回答:它正在覆蓋前2個元素,因爲每次執行for循環時都會通過執行list1 = []來重置它。

操作方法:這是因爲list1是輸入必要性,如果你想將其追加到list2它必須是新的。我建議創建一個新的變量,因爲它在邏輯上不兼容,試圖讓list1做到這一點。我使用下面的list_entry來實現您想要附加到list2的內容。 list1將按您的意願打印。

list1 = [] 
list2 = [] 
q = int(input("Quantos contatos deseja adicionar? ")) 
for i in range(q): 
    nome = input("Nome: ") 
    num = input("Número: ") 
    list1.append(nome) 
    list1.append(num) 
    list2.append([nome, num]) 

print(list1) 
print(list2) 

在進一步的說明nomenum被作爲附加功能是自反和它連接到不返回任何東西的對象進行操作返回空。

0

它會被覆蓋,因爲每次迭代時list1都會被重置。 試試這個:

list2 = [] 
q = int(input("Quantos contatos deseja adicionar? ")) 
list1 = [] 
for i in range(q): 
    list3 = [] 
    nome = list1.append(input("Nome: ")) 
    num = list1.append(input("Número: ")) 
    list3 = list1[(i*2):] 
    list2.append(list3) 

print(list1) 
print(list2) 

這給出了你提到的預期輸出。