Python中的zip()函數與zip(*)函數的作用

zip() 函數功能:

   將可迭代的對象作爲參數,將對象中對應的元素打包成一個個元組,然後返回由這些元組組成的列表。當各個迭代器中元素的個數不一致時,則返回列表中長度最短的情況,利用 *號操作符,可以將元組解壓爲列表。


代碼1:

strs1 = "flower"
strs2 = "flow"
strs3 = "flight"
print(list(zip(strs1, strs2)))
print(list(zip(strs2, strs3)))

結果爲:

[('f', 'f'), ('l', 'l'), ('o', 'o'), ('w', 'w')]
[('f', 'f'), ('l', 'l'), ('o', 'i'), ('w', 'g')]

代碼2:

strs = ["flower", "flow", "flight"]
print(list(zip(*strs)))   # 打包爲元組的列表
print(list(zip(strs)))

結果爲:

[('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]
[('flower',), ('flow',), ('flight',)]

拓展練習

快樂的LeetCode — 14. 最長公共前綴

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章