Heim  >  Artikel  >  Backend-Entwicklung  >  python中zip()方法应用实例分析

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

WBOY
WBOYOriginal
2016-06-10 15:05:131324Durchsuche

本文实例分析了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}

一个比较快捷的方法是用到内建方法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}

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

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

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

Stellungnahme:
Der Inhalt dieses Artikels wird freiwillig von Internetnutzern beigesteuert und das Urheberrecht liegt beim ursprünglichen Autor. Diese Website übernimmt keine entsprechende rechtliche Verantwortung. Wenn Sie Inhalte finden, bei denen der Verdacht eines Plagiats oder einer Rechtsverletzung besteht, wenden Sie sich bitte an admin@php.cn