1. 程式人生 > >【程式碼】小技巧,動態更新中。。。。

【程式碼】小技巧,動態更新中。。。。

若要在迴圈內部修改正在遍歷的序列(例如複製某些元素),建議您首先製作副本。在序列上迴圈不會隱式地建立副本。切片表示法使這尤其方便:

>>> words = ['cat', 'window', 'defenestrate']
>>> 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']
a
[1, 2, 3]
b
[4, 5, 6]
zipped = zip(a, b)
zip(*zipped)
<zip object at 0x0000000003643DC8>
list(zip(*zipped))
[]
zipped = list(zip(a, b))
zip(*zipped)
<zip object at 0x00000000036434C8>
list(zip(*zipped))
[(1, 2, 3), (4, 5, 6)]