使用zip()函數來可以把列表合並,並創建一個元組對的列表
我語言表達起來可能有些粗糙,話不多說看示例
#示例1
l1=[1,2,3] lt2=[4,5,6] lt3=zip(l1,lt2) #zip()是可迭代對象,使用時必須將其包含在一個list中,方便一次性顯示出所有結果 #print(lt3) #print(list(lt3)) #print(dict(lt3))
lt4=['dd','18','183'] lt5=['name','age','height'] a=zip(lt5,lt4) print(dict(a))
#zip()參數可以接受任何類型的序列,同時也可以有兩個以上的參數;
# 當傳入參數的長度不同時,zip能自動以最短序列長度為准進行截取
l1, l2, l3 = (1, 2, 3), (4, 5, 6), (7, 8, 9) print(list(zip(l1, l2, l3))) [(1, 4, 7), (2, 5, 8), (3, 6, 9)] str1 = 'abc' str2 = 'def123' print(list(zip(str1, str2))) [('a', 'd'), ('b', 'e'), ('c', 'f')]
##一個坑
###坑1
l1 = [1, 2, 3, 4] l2 = [2, 3, 4, 5] l3 = zip(l1, l2) for i in l3: print('for循環{}'.format(i)) l4 = [x for x in l3] print(l4)
#坑2
l1 = [1, 2, 3, 4] l2 = [2, 3, 4, 5] l3 = zip(l1, l2) l4 = [x for x in l3] print(l4) for i in l3: print('for循環{}'.format(i))
###for循環沒執行!!!,咋整的,查下zip看一下
##Return a zip object whose .__next__() method returns a tuple where
# the i-th element comes from the i-th iterable argument. The .__next__()
# method continues until the shortest iterable in the argument sequence
# is exhausted and then it raises StopIteration.
# 返回一個zip對象,其中.__next__()方法返回一個元組
# 第i個元素來自第i個可迭代參數。.__next__()
# 方法繼續執行,直到參數序列中最短的可迭代
# 耗盡,然后引發StopIteration。
#重點就是這個 “zip對象” 是一個迭代器。 迭代器只能前進,不能后退
#它空了,所以沒有執行,空的東西怎么遍歷