python3中的zip()、zip(*)、list()之间的灵活转换!

zip()、zip(*)、list()三者之间的转换主要是围绕zip()函数展开的,zip()函数的出现主要是为了减少编程中内存的使用,将可迭代的序列数据进行一定的压缩来达到目的。其他两者list()、zip()主要是为了配合做数据的解压与还原。

python3中的zip()、zip(*)、list()之间的灵活转换!

阅读全文

首先,初始化几组列表来作为原始数据用于后面的演示,然后通过zip()函数压缩这两组列表数据。

$ ipython
Python 3.8.6 (tags/v3.8.6:db45529, Sep 23 2020, 15:37:30) [MSC v.1927 32 bit (Intel)]
Type 'copyright', 'credits' or 'license' for more information
IPython 7.29.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: a = [1, 2, 3, 4, 5, 6, 7, 8]

In [2]: b = [10, 9, 8, 7, 6, 5, 4, 3]

In [3]: zip_obj = zip(a, b)
print(zip_obj)

In [4]: print(list(zip_obj))
[(1, 10), (2, 9), (3, 8), (4, 7), (5, 6), (6, 5), (7, 4), (8, 3)]

再通过zip(*)函数将其解压

In [8]: a1, a2 = zip(*zip(a,b))
In [9]: print(a1)
(1, 2, 3, 4, 5, 6, 7, 8)

In [10]: print(a2)
(10, 9, 8, 7, 6, 5, 4, 3)

In [11]: list(a1)
Out[11]: [1, 2, 3, 4, 5, 6, 7, 8]

In [12]: list(a2)
Out[12]: [10, 9, 8, 7, 6, 5, 4, 3]

python3中的zip()、zip(*)、list()之间的灵活转换!

【往期精彩】

python print() 函数的格式化字符串输出

● PyQt5 GUI && Requests Api 做一个天气查询系统(文末领取完整代码)!

● 一款优美的windows cmd命令行工具cmder

● excel数据处理二:快速完成openpyxl数据的新增、修改!

● 如何进行excel数据分析之后的可视化数据写入保存!

● excel数据处理一:巧妙使用openpyxl提取、筛选数据

● 比Selenium更方便的自动化测试工具Helium!

● Python数据可视化:可视化数据分析插件D-Tale

● 冒泡排序、选择排序之间的比较与代码实现!

● 计算速度太慢?试试 lru_cache 装饰器!

Original: https://www.cnblogs.com/lwsbc/p/15700209.html
Author: Python集中营
Title: python3中的zip()、zip(*)、list()之间的灵活转换!

原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/510520/

转载文章受原作者版权保护。转载请注明原作者出处!

(0)

大家都在看

亲爱的 Coder【最近整理,可免费获取】👉 最新必读书单  | 👏 面试题下载  | 🌎 免费的AI知识星球