2017-09-08 57 views
0

列表改寫項比方說,我有一個列表:基於輸入指數

lst = [1,2,3,4] 

和我提示用戶輸入索引和項目。然後程序將查找列表中的索引位置,並用列表中的元素替換用戶輸入項。例如:

enter index: 2 
enter item to replace: 5 

輸出將是:

[1,2,5,4] 

這是我已經試過:

lst = [1,2,3,4] 

index = int(input("Enter index: ")) 
item = int(input("Enter item to replace: ")) 

i = 0 
n = len(lst) 
while i<n: 
    if i == index: 
     lst[i] = item 
    else: 
     i+=1 
print(lst) 

我不知道爲什麼它不打印出任何東西,我很確定邏輯是寫的,但我猜我的問題是在while循環內?

+3

爲什麼要使用循環?當你可以做'lst [index] = item' –

+0

你的while循環被困住了,因爲當i ==索引時你永遠不會增加i ..所以一旦它到達並替換了索引,它就會被困在while循環中 – AK47

+0

如果你只是想替換@Moses的解決方案的值是正確的。但請記住,如果您想要在索引4處添加一個新值(在列表末尾插入第五項),則失敗。然後你需要append方法。 – Igle

回答

1

while循環永遠不會終止,因爲那裏是從來沒有爲i值完成後i == index任何增量 - 因此while循環被被困在一個無限循環,它永遠不會到達節目結束時打印出清單

lst = [1,2,3,4] 

index = int(input("Enter index: ")) 
item = int(input("Enter item to replace: ")) 

i = 0 
n = len(lst) 
while i<n: 
    if i == index: 
     lst[i] = item 
    i+=1 
print(lst) 
2

正如指出的@MosesKoledoye你可以用簡單的indexing

lst = [1,2,3,4] 

index = int(input("Enter index: ")) 
item = int(input("Enter item to replace: ")) 

lst[index] = item 

Enter index: 2 

Enter item to replace: 5 

print(lst) 
[1, 2, 5, 4] 

記住名單0索引。如果你想使用1索引列表,只需使用lst[index + 1] = item

+0

'lst [index] = 3' for'index'數字不是一個分片,它是一個簡單的賦值。切片意味着同時索引更多元素 – GPhilo

+0

@GPhilo謝謝,更正。雖然在技術上,不是['切片(停止)'](https://docs.python.org/3/library/functions.html#slice)一個有效的切片?這一點總是讓我困惑。 –