簡體   English   中英

Python數據結構:python中兩種類型的for循環之間的區別?

[英]Python Data Structure: Difference between two types of for-loop in python?

我當時以為應該問這個問題,但是我還是找不到(請在評論部分告訴我,如果有的話,我會刪除這篇文章)

引起我注意的是,當我們進行列表替換時,僅當我們按索引循環遍歷列表時,它才起作用。 為什么?

myList = ['a','b','c','d','e']
for item in myList:
    if item == 'a':
        item = 's'
print("First loop:",myList)           //It prints ['a','b','c','d','e']


for i in range(len(myList)):
    if myList[i] == 'a':
        myList[i] = 's'
print("Second loop:",myList)          //It prints ['s','b','c','d','e']

我已經嘗試閱讀python控制流文檔: https : //docs.python.org/3/tutorial/controlflow.html,但它並不能真正回答我的問題。

在第一個循環中,line item = 's'僅更改循環內的語言環境變量item的值,該值在每次迭代中由列表中的下一個值更新。 它不是對列表本身的引用。

在您的第一個for循環中,“ item”只是一個變量,該變量被分配給循環必須到達的任何列表項。 重新分配變量不會影響列表。 在第二個循環中,您直接更改列表項,這就是為什么在打印列表時顯示它。

在第一個循環的每次迭代中,變量item都分配給列表中的每個項。 如果滿足if條件,則僅將變量item重新分配為's' ,但這不會更改列表的內容。

在第二個循環中,您將重新分配my_list的內容,因為您將第i個項目分配給該行的's'

    myList[i] = 's'

還考慮一個更簡單的示例:

    myList = ['a', 'b', 'c']
    item = myList[0]  # assign item to 'a'
    item = 's'  # re-assign item variable to 's', does not change list
    myList[0] = 's'  # change the content of the first item in the list

還可以看一下: Python:何時通過引用傳遞變量,何時按值傳遞變量?

有關為什么第一個循環不起作用的示例,請檢查以下內容:

myList = ['a','b','c','d','e']
item = myList[0]
item = 's'

# this is an example equivalent to what the first loop does
# the values in myList remain unchanged

還有一個等效於第二個循環的示例:

myList = ['a','b','c','d','e']
myList[0] = 's'

# the first value in myList is changed to 's'

暫無
暫無

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

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