Python程式設計入門之for語句

The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended):Python中的for語句與C或PASCAL中使用的不同。而不是總是在算術級數(例如PASCAL)上迭代,或者給使用者定義迭代步驟和停止條件(如C)的能力,Python 中 for語句在任意序列(列表或字串)的項上迭代,按照它們所提出的順序。序列中的R。例如(沒有雙關語):

>>> # Measure some strings: 測量字串長度(例子)

。。。 words = [‘cat’, ‘window’, ‘defenestrate’] #建立一個列表

>>> for w in words:

。。。 print(w, len(w))

。。。

cat 3

window 6

defenestrate 12

If you need to modify the sequence you are iterating over while inside the loop (for example to duplicate selected items), it is recommended that you

first make a copy。 Iterating over a sequence does not implicitly make a copy。 The slice notation makes this especially convenient:如果需要修改迴圈內迴圈的順序(例如複製選定項),建議您先複製。迭代一個序列不會隱式複製。切片符號使這特別方便:

>>> for w in words[:]: # Loop over a slice copy of the entire list。迴圈遍歷整個列表的切片(擷取段)副本

。。。 if len(w) > 6:

。。。 words。insert(0, w)

。。。

>>> words

[‘defenestrate’, ‘cat’, ‘window’, ‘defenestrate’]

With for w in words:, the example would attempt to create an infinite list, inserting defenestrate over and over again.

以W為詞:示例將嘗試建立一個無限列表,一次又一次插入預設的列表。

Python程式設計入門之for語句