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

yipeiwu_com7年前Python基础

本文实例讲述了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") 

在我电脑上的测试结果:

map 1.06299996376s 
lst 0.296000003815s 

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

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

相关文章

Python中List.index()方法的使用教程

 index()方法返回obj出现在列表中最低位索引。 语法 以下是index()方法的语法: list.index(obj) 参数   &...

pyinstaller打包程序exe踩过的坑

pyinstaller打包程序exe踩过的坑

基础环境 python 2.7.17 pyinstaller 3.5 安装pyinstaller pip install pyinstaller 坑,大坑,深坑 背景:...

解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available

解决安装python3.7.4报错Can''t connect to HTTPS URL because the SSL module is not available

简述 从官网下载了Python3.7.4,直接编译安装后,使用pip3出现了报错信息: Can't connect to HTTPS URL because the SSL module...

使用python脚本自动创建pip.ini配置文件代码实例

这篇文章主要介绍了使用python脚本自动创建pip.ini配置文件代码实例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 运行一下p...

Python写的贪吃蛇游戏例子

第一次用Python写这种比较实用且好玩的东西,权当练手吧 游戏说明: * P键控制“暂停/开始”* 方向键控制贪吃蛇的方向 源代码如下:复制代码 代码如下:from Tkinter i...