Python [zip() function, zip(*) function]

zip() function:

\quad \quad Take the iterable object as a parameter, pack the corresponding elements in the object into tuples, and then return a list of these tuples. When the number of elements in each iterator is inconsistent, the shortest length in the list is returned,

zip(*) function

\quad \quad Using the * operator, you can decompress the tuple into a list.

python 2.x and python3.x version

  • In python2.x version, the zip function returns a list.
  • What python3.x generates is an iterable object, which needs to be processed by list() and the data is extracted.

Python2.x version
Code 1: Array

>>> a=[1,2,3]
>>> b=[4,5,6]
>>> c=[9,8,7,6,3]
>>> zip(a,b)
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c)
[(1, 9), (2, 8), (3, 7)]
>>> d=zip(a,c)
>>> zip(*d)
[(1, 2, 3), (9, 8, 7)]

Code 2: String

>>> strs1 = "flower"
>>> strs2 = "flow"
>>> strs3 = "flight"
>>> zip(strs1,strs2)
[('f', 'f'), ('l', 'l'), ('o', 'o'), ('w', 'w')]
>>> zip(strs2,strs3)
[('f', 'f'), ('l', 'l'), ('o', 'i'), ('w', 'g')]
>>> strs=[strs1,strs2,strs3]
>>> zip(*strs)
[('f', 'f', 'f'), ('l', 'l', 'l'), ('o', 'o', 'i'), ('w', 'w', 'g')]
  • Through this example, we can actually be used to solve the problem of common prefixes of strings

Python3.x version

Insert picture description here

Guess you like

Origin blog.csdn.net/weixin_45666566/article/details/112424824