Heim  >  Artikel  >  Backend-Entwicklung  >  Python判断值是否在list或set中的性能对比分析

Python判断值是否在list或set中的性能对比分析

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

本文实例对比分析了Python判断值是否在list或set中的执行性能。分享给大家供大家参考,具体如下:

判断值是否在set集合中的速度明显要比list快的多, 因为查找set用到了hash,时间在O(1)级别。

假设listA有100w个元素,setA=set(listA)即setA为listA转换之后的集合。
以下做个简单的对比:

for i in xrange(0, 5000000):
  if i in listA:
     pass
for i in xrange(0, 5000000):
  if i in setA:
     pass

第一个循环用了16min,第二个循环用了52s。 由此可见,在set中判断是否存在某值的效率要高的多。

况且,从list转为set,并不会花什么时间。

更多关于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