Python zip function and usage

The zip () function is one of Python's built-in functions. It can "compress" multiple sequences (lists, tuples, dictionaries, sets, strings, and lists of range () intervals) into a zip object. The so-called "compression" is actually to regroup the elements in the corresponding positions in these sequences to generate new tuples.

Unlike the Python 3.x version, the zip () function in the Python 2.x version will directly return the list instead of returning the zip object. However, the returned list or zip object contains the same elements (all tuples).

The syntax of the zip () function is:

zip(iterable, ...)

Where iterable, ... means multiple lists, tuples, dictionaries, sets, strings, and even range () intervals. https://www.furuihua.cn/pingtai/

The following program demonstrates the basic usage of the zip () function:

  1. my_list = [11,12,13]
  2. my_tuple = (21,22,23)
  3. print([x for x in zip(my_list,my_tuple)])
  4. my_dic = {31:2,32:4,33:5}
  5. my_set = {41,42,43,44}
  6. print([x for x in zip(my_dic)])
  7. my_pychar = "python"
  8. my_shechar = "shell"
  9. print([x for x in zip(my_pychar,my_shechar)])

The program execution result is:

[(11, 21), (12, 22), (13, 23)]
[(31,), (32,), (33,)]
[('p', 's'), ('y', 'h'), ('t', 'e'), ('h', 'l'), ('o', 'l')]

If the reader analyzes the above program and the corresponding output results, it is not difficult to find that when using the zip () function to "compress" multiple sequences, it will take the first element, the second element in each sequence, respectively ... n elements, each forming a new tuple. It should be noted that when the number of elements in multiple sequences is inconsistent, compression will be based on the shortest sequence.

In addition, for the zip object returned by the zip () function, you can extract the stored tuples by traversing like the above program, or you can force the zip () object to be converted into a list by calling the list () function like the following program :

  1. my_list = [11,12,13]
  2. my_tuple = (21,22,23)
  3. print(list(zip(my_list,my_tuple)))

The program execution result is:

[(11, 21), (12, 22), (13, 23)]

Guess you like

Origin www.cnblogs.com/furuihua/p/12691927.html