簡體   English   中英

Python3:使用 function 和 while 循環更改列表中的項目。 為什么我的代碼運行不正常?

[英]Python3: Change the items on a list with function and while loop. Why is my code not running properly?

在執行以下任務時,我發現我的代碼沒有在 Jupiter 筆記本上正常運行(已經多次重新啟動 Kernel):

Function 挑戰:創建替換 function

創建一個 function,str_replace,需要 2 個 arguments:int_list 和 index

int_list 是個位整數的列表

index 是要檢查的索引 - 例如 int_list[index]

Function 復制上述任務“替換列表中的項目”的目的,並用字符串“小”或“大”替換 integer

返回 int_list

測試功能!

我的目標是使用以下代碼將列表 [0,1,2,3,4] 的所有元素更改為 ["small","small", "small","small","small"]:

int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
    if index <5:
        int_list[index]="small"
        return int_list
    else:
        int_list[index]="large"
        return int_list

str_replace(int_list,index)
while index <=4:
    index+=index
    str_replace(int_list,index)

當我運行它時,它一直在運行並且沒有給我任何 output。 但是,如果我運行除了最后一個 while 循環之外的所有內容,我會得到:["small",1,2,3,4]。 誰能幫我理解為什么會這樣?

您處於無限循環中: index始終 <= 4。請參閱: index已初始化為 0,並且新的賦值index+=index永遠不會將 index 的值更改為高於 0。您的意思是index += 1嗎?

您處於無限循環中,因為索引始終小於 4,

你做index += index但因為 index 是 0 什么都沒有加起來,你就留在循環中。

如果您將其更改為index += 1 - 那應該可以解決您的問題。

另外,為了不出現out of range錯誤,請將其更改為while index < 4:或者將index +=1放在循環的底部。

我認為問題在於每次更改時的返回語句

int_list=[0,1,2,3,4]
index=0
def str_replace(int_list,index):
if index <5:
    int_list[index]="small"

else:
    int_list[index]="large"


while index <=4:
str_replace(int_list,index)
index+=1

print(int_list)

另一種方法是使用

[ 'small' if index < 5 else 'large' for index in int_list]
int_list=[0,1,2,3,6]
index=0
def str_replace(int_list,index):
    if int_list[index] < 5:
        int_list[index] = "small"
    else:
        int_list[index] = "large"

while index <=4:
    str_replace(int_list,index)
    index+=1

print(int_list)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM