黃哥Python:回答知乎上二個有關for 循環問題
來自專欄 通過python學會編程
大概只有初學者,死磕語法者才會提出這樣的問題。
第一問題:
Python中for循環之後的參數和in之後的目標相同,為什麼還能運行?for之後的參數是什麼性質的?
n = [1,2,[3,4,[5,6]]]
def print_lol(n): for n in n: if isinstance(n,list):print_lol(n)
else: print(n)print_lol(n) #能正常運行1
23456
請問,for之後的n和名字為n的列表兩個參數同名, 為什麼還能正常運行?第二個網友的問題,現在找不到鏈接了,黃哥憑記憶,他的代碼如下:
a = [[1, 2], [3, 4]]for i in a: i = [1, 1]print(a)for i in range(len(a)): a[i] = [1, 1]print(a)
他的問題,是問,為啥第一個循環,不能修改a的值,第二個循環可以。
下面請看黃哥的分析和解答:
The "for" statement*******************The "for" statement is used to iterate over the elements of a sequence(such as a string, tuple or list) or other iterable object: for_stmt ::= "for" target_list "in" expression_list ":" suite ["else" ":" suite]The expression list is evaluated once; it should yield an iterableobject. An iterator is created for the result of the"expression_list". The suite is then executed once for each itemprovided by the iterator, in the order returned by the iterator. Eachitem in turn is assigned to the target list using the standard rulesfor assignments (see Assignment statements), and then the suite isexecuted. When the items are exhausted (which is immediately when thesequence is empty or an iterator raises a "StopIteration" exception),the suite in the "else" clause, if present, is executed, and the loopterminates.A "break" statement executed in the first suite terminates the loopwithout executing the "else" clauses suite. A "continue" statementexecuted in the first suite skips the rest of the suite and continueswith the next item, or with the "else" clause if there is no nextitem.The for-loop makes assignments to the variables(s) in the target list.This overwrites all previous assignments to those variables includingthose made in the suite of the for-loop: for i in range(10): print(i) i = 5 # this will not affect the for-loop # because i will be overwritten with the next # index in the rangeNames in the target list are not deleted when the loop is finished,but if the sequence is empty, they will not have been assigned to atall by the loop. Hint: the built-in function "range()" returns aniterator of integers suitable to emulate the effect of Pascals "for i:= a to b do"; e.g., "list(range(3))" returns the list "[0, 1, 2]".Note: There is a subtlety when the sequence is being modified by the loop (this can only occur for mutable sequences, i.e. lists). An internal counter is used to keep track of which item is used next, and this is incremented on each iteration. When this counter has reached the length of the sequence the loop terminates. This means that if the suite deletes the current (or a previous) item from the sequence, the next item will be skipped (since it gets the index of the current item which has already been treated). Likewise, if the suite inserts an item in the sequence before the current item, the current item will be treated again the next time through the loop. This can lead to nasty bugs that can be avoided by making a temporary copy using a slice of the whole sequence, e.g., for x in a[:]: if x < 0: a.remove(x)Related help topics: break, continue, while
上面是for 循環的文檔,
for_stmt ::= "for" target_list "in" expression_list ":" suite
["else" ":" suite]
The expression list is evaluated once; it should yield an iterable
object.
for n in n in 後面的n 變成了可迭代對象。前面的n是一個變數。所以二個n 不相關。
但不推薦這樣命名。
for i in a: i = [1, 1]print(a)這個也是同樣的道理, a 變成了可迭代對象, i是變數,i的改變不能影響到a。
總結:黃哥Python提醒,對語法不能死磕,要找到問題所在,要去看文檔,有的初學者非要整一個明白,如果非要搞清楚原理,要去看cpython 的c代碼,Python 代碼都看不懂,能有能力去看C 語言代碼嗎?所以適當的時候要不求甚解,這是好的學習方法。
黃哥:黃哥寫的對Python初學者有價值的文章。推薦閱讀:
※Python爬蟲之scrapy從入門到忘記
※ELEMENTARY.01.Say Hi
※泰坦尼克號生存率預測練習(2)
※跟黃哥學python之函數是第一類對象
※關於Python中參數傳遞和作用域的問題?
TAG:Python |