Home > Backend Development > Python Tutorial > python中zip()方法应用实例分析

python中zip()方法应用实例分析

WBOY
Release: 2016-06-10 15:05:13
Original
1382 people have browsed it

本文实例分析了python中zip()方法的应用。分享给大家供大家参考,具体如下:

假设有一个集合set, 需要对set中的每个元素指定一个唯一的id,从而组建成一个dict结构。
这个场景可以演化成,两个list/set或者一个set与一个list如何创建成为一个字典,如:

A = ["a", "b", "c", "d"]
B = [1, 2, 3, 4]
?  ==>
C = {"a":1, "b":2, "c":3, "d":4}

Copy after login

一个比较快捷的方法是用到内建方法zip()来实现。示例如下:

>>> A = ["a", "b", "c", "d"]
>>> B = [1, 2, 3, 4]
>>>
>>> C = dict(zip(A, B))
>>> C
{'a': 1, 'c': 3, 'b': 2, 'd': 4}
>>> E = range(0, len(A))
>>> F = dict(zip(A, E))
>>> F
{'a': 0, 'c': 2, 'b': 1, 'd': 3}

Copy after login

zip,dict都为build-in方法,其效率都很高。对于长度百万级别的list,耗时也不过十来秒(不过当然和机器自身性能有关了:-) )

更多关于Python相关内容感兴趣的读者可查看本站专题:《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》

希望本文所述对大家Python程序设计有所帮助。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template