Go Python fragmented Knowledge (2): powerful zip

Source: Internet
Author: User
Tags python list

First, code guidance

First look at this section of code:

1 >>> name=(‘jack‘,‘beginman’,‘sony‘,‘pcky’)
  2 >>> age=(2001, 2003, 2005, 2000)
  3 >>> for a,n in zip(name,age):
  4 print a,n
  5
  6 output:
  7 jack 2001
  8 beginman 2003
  9 sony 2005
10 pcky 2000

Let's look at this section of code:

1 all={"jack":2001,"beginman":2003,"sony":2005,"pcky":2000}
2 for i in all.keys():
3 print i,all[i]
4
5 output:
6 sony 2005
7 pcky 2000
8 jack 2001
9 beginman 2003

Find the difference between them?

The most obvious is: the first is concise, flexible, and can be entered sequentially.

Two, zip () function

It is the built-in function of Python (the built-in functions associated with the sequence are: sorted (), reversed (), enumerate (), zip ()), where sorted () and zip () return a sequence (list) object, reversed (), Enumerate () returns an iterator (similar to a sequence)

1 >>> type(sorted(s))
2 <type ‘list‘>
3 >>> type(zip(s))
4 <type ‘list‘>
5 >>> type(reversed(s))
6 <type ‘listreverseiterator‘>
7 >>> type(enumerate(s))
8 <type ‘enumerate‘>

So what is the zip () function?

We help (Zip) to see:

1 >>> help(zip)
2 Help on built-in function zip in module __builtin__:
3 
4 zip(...)
5     zip(seq1 [, seq2 [...]]) -> [(seq1[0], seq2[0] ...), (...)]
6     
7     Return a list of tuples, where each tuple contains the i-th element
8     from each of the argument sequences.  The returned list is truncated
9     in length to the length of the shortest argument sequence.

Hint: Do not understand a certain number of help

Definition: Zip ([seql, ...]) Accepts a series of iterative objects as parameters, packages the corresponding elements in the object into tuple (tuples), and then returns a list of these tuples (lists). If the length of the passed parameter is not equal, the length of the returned list is the same as the object with the shortest length in the parameter.

 1 >>> z1=[1,2,3]
 2 >>> z2=[4,5,6]
 3 >>> result=zip(z1,z2)
 4 >>> result
 5 [(1, 4), (2, 5), (3, 6)]
 6 >>> z3=[4,5,6,7]
 7 >>> result=zip(z1,z3)
 8 >>> result
 9 [(1, 4), (2, 5), (3, 6)]
10 >>> 

The zip () Mate * operator allows you to unzip a list object that has already been zipped

1 >>> zip(*result)
2 [(1, 2, 3), (4, 5, 6)]

More on the next level of understanding:
Content Source: http://www.cnblogs.com/diyunpeng/archive/2011/09/15/2177028.html (Blog Park talent really many!) )

* Two-dimensional matrix transformation (matrix row and column interchange)
For example, we have a two-dimensional matrix described by a list.
a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
We can also do this task easily through the python list derivation method.
Print [ [row[col] for row in a] for col in range(len(a[0]))]
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
Another confusing way is to use the zip function:
>>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> zip(*a)
[(1, 4, 7), (2, 5, 8), (3, 6, 9)]
>>> map(list,zip(*a))
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
 
The zip function accepts any number of sequences as parameters, and combines all sequences into the same index into one element, which is a new sequence of tuples in which the sequences are combined. The length of the new sequence is based on the shortest sequence of parameters. In addition, the (*) operator cooperates with the zip function to implement the opposite function of zip, which is to split the merged sequence into multiple tuples.
New sequence of 1tuple
>>>>x=[1,2,3],y=[‘a‘,‘b‘,‘c’]
>>>zip(x,y)
[(1, ‘a‘), (2, ‘b’), (3, ‘c’)]

2 The length of the new sequence is based on the shortest sequence of parameters.
>>>>x=[1,2],y=[‘a‘,‘b‘,‘c’]
>>>zip(x,y)
[(1,‘a‘),(2,‘b‘)]

The 3(*) operator works in conjunction with the zip function to implement the opposite of zip, which splits the merged sequence into multiple tuples.
>>>>x=[1,2,3],y=[‘a‘,‘b‘,‘c’]
>>>>zip(*zip(x,y))
[(1,2,3),(‘a‘,‘b‘,‘c’)]

Other advanced applications:

1.zip package unpacking list and multiples
>>> a = [1, 2, 3]
>>> b = [‘a‘, ‘b‘, ‘c‘]
>>> z = zip(a, b)
>>> z
[(1, ‘a‘), (2, ‘b’), (3, ‘c’)]
>>> zip(*z)
[(1, 2, 3), (‘a‘, ‘b‘, ‘c‘)]

2. Use zip to merge adjacent list items

>>> a = [1, 2, 3, 4, 5, 6]
>>> zip(*([iter(a)] * 2))
[(1, 2), (3, 4), (5, 6)]

>>> group_adjacent = lambda a, k: zip(*([iter(a)] * k))
>>> group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]
>>> group_adjacent(a, 2)
[(1, 2), (3, 4), (5, 6)]
>>> group_adjacent(a, 1)
[(1,), (2,), (3,), (4,), (5,), (6,)]

>>> zip(a[::2], a[1::2])
[(1, 2), (3, 4), (5, 6)]

>>> zip(a[::3], a[1::3], a[2::3])
[(1, 2, 3), (4, 5, 6)]

>>> group_adjacent = lambda a, k: zip(*(a[i::k] for i in range(k)))
>>> group_adjacent(a, 3)
[(1, 2, 3), (4, 5, 6)]
>>> group_adjacent(a, 2)
[(1, 2), (3, 4), (5, 6)]
>>> group_adjacent(a, 1)
[(1,), (2,), (3,), (4,), (5,), (6,)]

3. Use zip and iterators to generate sliding windows (n -grams)
>>> from itertools import islice
>>> def n_grams(a, n):
... z = (islice(a, i, None) for i in range(n))
... return zip(*z)
...
>>> a = [1, 2, 3, 4, 5, 6]
>>> n_grams(a, 3)
[(1, 2, 3), (2, 3, 4), (3, 4, 5), (4, 5, 6)]
>>> n_grams(a, 2)
[(1, 2), (2, 3), (3, 4), (4, 5), (5, 6)]
>>> n_grams(a, 4)
[(1, 2, 3, 4), (2, 3, 4, 5), (3, 4, 5, 6)]

4. Use the zip reverse dictionary
>>> m = {‘a‘: 1, ‘b’: 2, ‘c’: 3, ‘d’: 4}
>>> m.items()
[(‘a‘, 1), (‘c‘, 3), (‘b‘, 2), (‘d‘, 4)]
>>> zip(m.values(), m.keys())
[(1, ‘a‘), (3, ‘c’), (2, ‘b’), (4, ‘d’)]
>>> mi = dict(zip(m.values(), m.keys()))
>>> mi
{1: ‘a‘, 2: ‘b’, 3: ‘c’, 4: ‘d’}
(original address: http://www.cnblogs.com/BeginMan/archive/2013/03/14/2959447.html)

Go Python fragmented Knowledge (2): powerful zip

Related Article
Large-Scale Price Reduction
  • 59% Max. and 23% Avg.
  • Price Reduction for Core Products
  • Price Reduction in Multiple Regions
undefined. /
Connect with us on Discord
  • Secure, anonymous group chat without disturbance
  • Stay updated on campaigns, new products, and more
  • Support for all your questions
undefined. /
Free Tier
  • Start free from ECS to Big Data
  • Get Started in 3 Simple Steps
  • Try ECS t5 1C1G
undefined. /

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.