Python zip () function usage

Source: Internet
Author: User

Zip ()--built-in functions

Zip ([iterable, ...])
It takes a series of iterated objects as parameters, packages the corresponding elements in the object into a tuple (tuple), and returns a list of these tuples.
If the length of the passed parameter is unequal, the length of the returned list is the same as the object with the shortest length in the parameter;

With Dict (), the list group synthesis dictionary can be completed;

Note: Python3 current zip function print output does not display properly, such as: <zip object at 0x0000000002598548>

Usage examples:

Readers look at the following example, the basic use of the zip () function is clear:

1>>> a = [a]2>>> B = [4,5,6]3>>> C = [4,5,6,7,8]4>>> n =Zip (A, b)5[(1, 4), (2, 5), (3, 6)]6>>>Zip (a,c)7[(1, 4), (2, 5), (3, 6)]8>>>Zip (a)9[(1,), (2,), (3,)]Ten>>> Zip (*N) One[(1, 2, 3), (4, 5, 6)]

Note: Using *list/tuple in a function call means separating the list/tuple, passing it as a positional parameter to the corresponding function (provided that the corresponding function supports an indefinite number of positional parameters)

1 >>> a = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]2 >>> Zip (*a)3 [  (1, 4, 7), (2, 5, 8), (3, 6, 9)]4 >>> Map (list,zip (*a))5 [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

This method is faster but more difficult to understand, the list as a tuple decompression, just get our "Row and column swap" effect, and then by applying the list () function to each element, convert the tuple to list

1 >>> x = [1, 2, 3]2 >>> r = Zip (* [x] * 3)3print c6> R4 [(1, 1, 1), (2, 2, 2), (3, 3, 3)]

The operating mechanism is this:

[x] generates a list of lists that have only one element x

[x] * 3 generates a list of lists, it has 3 elements, [x, X, X]

The meaning of Zip (* [x] * 3) is clear, zip (x, x, x)

Python zip () function usage

Related Article

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.