>>> # 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 youfirst 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为词:示例将尝试创建一个无限列表,一次又一次插入缺省的列表。