1. 程式人生 > >python多個變數的for迴圈

python多個變數的for迴圈

當for迴圈有兩個需要迭代的物件時,要用zip對這多個變數封裝,否則會報錯“too many values to unpack”

錯誤的例子:

starts = [0,1,2,3,4]
ends = [5,6,7,8,9]
for start, end in starts, ends:
    print((start, end))

正確的例子:

starts = [0,1,2,3,4]
ends = [5,6,7,8,9]
for start, end in zip(starts, ends):
    print((start, end))