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

yipeiwu_com6年前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程序设计有所帮助。

相关文章

Django 模型类(models.py)的定义详解

Django 模型类(models.py)的定义详解

一. #在models.py中添加 #代码如下 from django.db import models #出版商 class Publisher(models.Model):...

Python中isnumeric()方法的使用简介

 isnumeric()方法检查字符串是否仅由数字组成。这种方法只表示为Unicode对象。 注意:要定义一个字符串为Unicode,只需前缀分配'u'引号。以下是示例。 语法...

Python base64编码解码实例

Python中进行Base64编码和解码要用base64模块,代码示例: #-*- coding: utf-8 -*- import base64 str = 'cnblogs'...

对python 中re.sub,replace(),strip()的区别详解

对python 中re.sub,replace(),strip()的区别详解

1.strip(): str.strip([chars]);去除字符串前面和后面的所有设置的字符串,默认为空格 chars -- 移除字符串头尾指定的字符序列。 st = " he...

朴素贝叶斯分类算法原理与Python实现与使用方法案例

朴素贝叶斯分类算法原理与Python实现与使用方法案例

本文实例讲述了朴素贝叶斯分类算法原理与Python实现与使用方法。分享给大家供大家参考,具体如下: 朴素贝叶斯分类算法 1、朴素贝叶斯分类算法原理 1.1、概述 贝叶斯分类算法是一大类分...