解决Python3下map函数的显示问题

yipeiwu_com6年前Python基础

map函数是Python里面比较重要的函数,设计灵感来自于函数式编程。Python官方文档中是这样解释map函数的:

map(function, iterable, ...)

Return an iterator that applies function to every item of iterable, yielding the results. If additional iterable arguments are passed, function must take that many arguments and is applied to the items from all iterables in parallel. With multiple iterables, the iterator stops when the shortest iterable is exhausted.

即map函数接收的第一个参数为一个函数,可以为系统函数例如float、或者def定义的函数、或者lambda定义的函数均可。

举一个简单的例子,下面这个例子在Python2.7下是可以正常显示的:

ls = [1,2,3]
rs = map(str, ls)
 #打印结果
['1', '2', '3']
lt = [1, 2, 3, 4, 5, 6]
def add(num):
  return num + 1
rs = map(add, lt)
print rs
#[2,3,4,5,6,7]

但是在Python3下我们输入:

ls=[1,2,3]
rs=map(str,ls)
print(rs)

显示的却是:

<map at 0x3fed1d0>

而不是我们想要的结果,这也是Python3下发生的一些新的变化,如果我们想得到需要的结果需要这样写:

ls=[1,2,3]
rs=map(str,ls)
print(list(rs))

这样显示的结果即为我们想要看到的。这一点在《机器学习实战》的第10章中会有一点帮助。

以上这篇解决Python3下map函数的显示问题就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

python 获取图片分辨率的方法

pil版: from PIL import Image filename = r'E:\data\yangben\0.jpg' img = Image.open(filename)...

Swift中的协议(protocol)学习教程

一、引言 协议约定了一些属性与方法,其作用类似Java中的抽象类,Swift中类型通过遵守协议来实现一些约定的属性和方法。Swift中的协议使用protocol关键字来声明。Swift中...

Django项目后台不挂断运行的方法

方法一: 1、进入项目目录下,运行下面程序: nohup python manage.py runserver 0.0.0.0:5008 & nohup(no hang up)用...

Python的Django框架使用入门指引

Python的Django框架使用入门指引

 前言 传统 Web 开发方式常常需要编写繁琐乏味的重复性代码,不仅页面表现与逻辑实现的代码混杂在一起,而且代码编写效率不高。对于开发者来说,选择一个功能强大并且操作简洁的开发...

Python操作mongodb的9个步骤

一 导入 pymongo from pymongo import MongoClient 二 连接服务器 端口号 27017 连接MongoDB 连接MongoDB我们需要使用P...