python zip to use

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/selfimpro_001/article/details/90486478

Powerful zip

A. Zip () Introduction

  • zip () function is used as a parameter iterables, the corresponding element of the object packed into a tuple, and return the object of these tuples. If the number of elements of the various iterables inconsistent, then the object is the same as the shortest length of the returned object may be iterative.
  • * Operation zip () In contrast, the equivalent split into a tuple lists.

Two. Zip () syntax

zip(iterable1, iterable2, …)

iterable1, iterable2, ... are iterables, including: strings, lists, tuples, dictionaries.

III. Case Study

In [1]: id = ['1', '2', '3', '4']
In [2]: name = ['zhangsan', 'lisi', 'wangwu', 'xiaohua']
In [3]: weight = ['165', '140', '130', '110']
In [4]: zipped = zip(a,b)
In [5]: zipped = zip(id, name)
In [6]: print(zipped)
"""
<zip object at 0x000001C906467A88>  # 得到的是一个对象
"""
In [7]: print(list(zipped))    # list()方法可转换为列表
"""
[('1', 'zhangsan'), ('2', 'lisi'), ('3', 'wangwu'), ('4', 'xiaohua')]
"""

In [8]: list(zip(id, name, weight))  #  可同时对三个或者多个对象使用zip()
"""
[('1', 'zhangsan', '165'),
 ('2', 'lisi', '140'),
 ('3', 'wangwu', '130'),
 ('4', 'xiaohua', '110')]
"""
``In [9]: list(zip(*zipped))   # 把zip后的结果分开
"""
Out[10]: [('1', '2', '3', '4'), ('zhangsan', 'lisi', 'wangwu', 'xiaohua')]
"""

In [11]: test1 = [1, 2, 3, 4, 5]
In [12]: test2 = [6, 7, 8]
In [13]: list(zip(test1, test2))  # 对于长度不一样的,选取较短的长度为标准
“”“
Out[14]: [(1, 6), (2, 7), (3, 8)]
”“”

## 对于字典,zip()之后,字典的key组合到一个元祖中
dict1 = {'1': 'zhangsan', '2': 'lisi', '3': 'wangwu'}
dict2 = {'one': '110', 'two': '140', 'three': '90'}
dict1_and_dict2 = zip(dict1, dict2)
print(list(dict1_and_dict2))
“”“
[('1', 'one'), ('2', 'two'), ('3', 'three')]
”“”
list(zip(*zip(dict1, dict2)))
"""
[('1', '2', '3'), ('one', 'two', 'three')]
"""

Guess you like

Origin blog.csdn.net/selfimpro_001/article/details/90486478
Recommended