Home > Backend Development > Python Tutorial > Python中map和列表推导效率比较实例分析

Python中map和列表推导效率比较实例分析

WBOY
Release: 2016-06-06 11:18:43
Original
1232 people have browsed it

本文实例讲述了Python中map和列表推导效率比较。分享给大家供大家参考。具体分析如下:

直接来测试代码吧:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 
# list comprehension and map 
import time 
def test(f, name): 
  st = time.time() 
  f() 
  print '%s %ss'%(name, time.time()-st) 
TIMES = 1000 
ARR = range(10000) 
def tmap(): 
  i = 0 
  while (i<TIMES): 
    map(lambda x:x, ARR)     
    i = i+1 
def tlst(): 
  i = 0 
  while (i<TIMES): 
    [x for x in ARR]     
    i = i+1 
test(tmap, "map") 
test(tlst, "lst") 

Copy after login

在我电脑上的测试结果:

map 1.06299996376s 
lst 0.296000003815s 

Copy after login

很明显列表推导比map操作会快很多,都三倍速度了

希望本文所述对大家的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