获取map()以在Python 3.x中返回列表 [英] Getting a map() to return a list in Python 3.x

查看:33
本文介绍了获取map()以在Python 3.x中返回列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将列表映射为十六进制,然后在其他地方使用该列表.在python 2.6中,这很简单:

I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy:

A: Python 2.6:

A: Python 2.6:

>>> map(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']

但是,在Python 3.1中,以上代码会返回一个地图对象.

However, in Python 3.1, the above returns a map object.

B: Python 3.1:

B: Python 3.1:

>>> map(chr, [66, 53, 0, 94])
<map object at 0x00AF5570>

如何在Python 3.x上检索映射列表(如上面的 A 一样)?

How do I retrieve the mapped list (as in A above) on Python 3.x?

或者,还有更好的方法吗?我的初始列表对象大约有45个项目,并且id希望将其转换为十六进制.

Alternatively, is there a better way of doing this? My initial list object has around 45 items and id like to convert them to hex.

推荐答案

执行以下操作:

list(map(chr,[66,53,0,94]))

在Python 3+中,许多对可迭代对象进行迭代的进程自己返回迭代器.在大多数情况下,这最终会节省内存,并且应该使处理速度更快.

In Python 3+, many processes that iterate over iterables return iterators themselves. In most cases, this ends up saving memory, and should make things go faster.

如果您要做的只是最终遍历此列表,则无需将其转换为列表,因为您仍然可以像这样遍历map对象:

If all you're going to do is iterate over this list eventually, there's no need to even convert it to a list, because you can still iterate over the map object like so:

# Prints "ABCD"
for ch in map(chr,[65,66,67,68]):
    print(ch)

这篇关于获取map()以在Python 3.x中返回列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆