在 Python 3.x 中获取 map() 返回列表

发布于 2024-08-01 22:37:16 字数 487 浏览 9 评论 0原文

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

A: Python 2.6:

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

但是,在 Python 3.1 中,上面的内容返回一个地图对象。

B: Python 3.1:

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

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

或者,有更好的方法吗? 我的初始列表对象有大约 45 个项目,我想将它们转换为十六进制。

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:

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

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

B: Python 3.1:

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

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

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(11

娜些时光,永不杰束 2024-08-08 22:37:16

这样做:

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

在 Python 3+ 中,许多迭代可迭代对象的进程都会返回迭代器本身。 在大多数情况下,这最终会节省内存,并且应该会让事情进展得更快。

如果您最终要做的只是迭代此列表,则甚至不需要将其转换为列表,因为您仍然可以迭代 map 对象,如下所示:

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

Do this:

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

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.

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)
穿越时光隧道 2024-08-08 22:37:16

Python 3.5 中的新功能和简洁:

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

感谢额外的解包概括

更新

一直在寻找更短的方法,我发现这个也有效:

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

解包也可以在元组中工作。 注意末尾的逗号。 这使其成为 1 个元素的元组。 也就是说,它相当于 (*map(chr, [66, 53, 0, 94]),)

它比带有列表括号的版本只短了一个字符,但是,在我的意见,更好地写,因为你从星号开始 - 扩展语法,所以我觉得它更容易记住。 :)

New and neat in Python 3.5:

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

Thanks to Additional Unpacking Generalizations

UPDATE

Always seeking for shorter ways, I discovered this one also works:

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

Unpacking works in tuples too. Note the comma at the end. This makes it a tuple of 1 element. That is, it's equivalent to (*map(chr, [66, 53, 0, 94]),)

It's shorter by only one char from the version with the list-brackets, but, in my opinion, better to write, because you start right ahead with the asterisk - the expansion syntax, so I feel it's softer on the mind. :)

墨落成白 2024-08-08 22:37:16

你为什么不这样做:

[chr(x) for x in [66,53,0,94]]

这称为列表理解。 您可以在 Google 上找到大量信息,但是 这里是 Python (2.6) 的链接关于列表推导式的文档。 不过,您可能对Python 3 文档更感兴趣。

Why aren't you doing this:

[chr(x) for x in [66,53,0,94]]

It's called a list comprehension. You can find plenty of information on Google, but here's the link to the Python (2.6) documentation on list comprehensions. You might be more interested in the Python 3 documenation, though.

难如初 2024-08-08 22:37:16

返回列表的地图功能具有节省打字的优点,特别是在交互式会话期间。 您可以定义返回列表的lmap函数(类似于python2的imap):

lmap = lambda func, *iterable: list(map(func, *iterable))

然后调用lmap而不是map > 将完成以下工作:
lmap(str, x)list(map(str, x)) 短 5 个字符(本例中为 30%),并且肯定比 短[str(v) for v in x]。 您也可以为 filter 创建类似的函数。

对于原来的问题有一个评论:

我建议重命名为 Getting map() 以返回 Python 3.* 中的列表,因为它适用于所有 Python3 版本。 有没有办法做到这一点? – meawoppl 1 月 24 日 17:58

这样做是可能的,但这是一个非常糟糕的主意。 只是为了好玩,您可以(但不应该)这样做:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator

List-returning map function has the advantage of saving typing, especially during interactive sessions. You can define lmap function (on the analogy of python2's imap) that returns list:

lmap = lambda func, *iterable: list(map(func, *iterable))

Then calling lmap instead of map will do the job:
lmap(str, x) is shorter by 5 characters (30% in this case) than list(map(str, x)) and is certainly shorter than [str(v) for v in x]. You may create similar functions for filter too.

There was a comment to the original question:

I would suggest a rename to Getting map() to return a list in Python 3.* as it applies to all Python3 versions. Is there a way to do this? – meawoppl Jan 24 at 17:58

It is possible to do that, but it is a very bad idea. Just for fun, here's how you may (but should not) do it:

__global_map = map #keep reference to the original map
lmap = lambda func, *iterable: list(__global_map(func, *iterable)) # using "map" here will cause infinite recursion
map = lmap
x = [1, 2, 3]
map(str, x) #test
map = __global_map #restore the original map and don't do that again
map(str, x) #iterator
无人问我粥可暖 2024-08-08 22:37:16

转换我的旧评论 为了更好的可见性:对于完全没有 map 的“更好的方法”,如果您的输入已知是 ASCII 序数,那么转换为 bytes 通常要快得多> 并解码,类似于 bytes(list_of_ordinals).decode('ascii')。 这会为您提供一个 str 值,但如果您需要一个 list 来实现可变性等,您只需转换它即可(而且速度仍然更快)。 例如,在转换 45 个输入的 ipython 微基准测试中:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

如果将其保留为 str,则大约需要最快 map 时间的 20% > 解决方案; 即使转换回列表,它仍然不到最快 map 解决方案的 40%。 通过 bytesbytes.decode 进行批量转换,然后批量转换回 list 可以节省大量工作,但是请注意,仅当所有输入均为 ASCII 序数(或每个字符区域设置特定编码的某个字节的序数,例如 latin-1)时才有效。

Converting my old comment for better visibility: For a "better way to do this" without map entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes and decode, a la bytes(list_of_ordinals).decode('ascii'). That gets you a str of the values, but if you need a list for mutability or the like, you can just convert it (and it's still faster). For example, in ipython microbenchmarks converting 45 inputs:

>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)

If you leave it as a str, it takes ~20% of the time of the fastest map solutions; even converting back to list it's still less than 40% of the fastest map solution. Bulk convert via bytes and bytes.decode then bulk converting back to list saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1).

沙沙粒小 2024-08-08 22:37:16

除了 Python 3 中的上述答案之外,我们还可以简单地从 map 创建结果值的 list

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

我们可以通过另一个示例进行概括,其中我很震惊,地图上的操作也可以像正则表达式问题一样以类似的方式处理,我们可以编写函数来获取要映射的项目的列表并在同时。 前任。

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]

In addition to above answers in Python 3, we may simply create a list of result values from a map as

li = []
for x in map(chr,[66,53,0,94]):
    li.append(x)

print (li)
>>>['B', '5', '\x00', '^']

We may generalize by another example where I was struck, operations on map can also be handled in similar fashion like in regex problem, we can write function to obtain list of items to map and get result set at the same time. Ex.

b = 'Strings: 1,072, Another String: 474 '
li = []
for x in map(int,map(int, re.findall('\d+', b))):
    li.append(x)

print (li)
>>>[1, 72, 474]
凉月流沐 2024-08-08 22:37:16

您可以尝试通过迭代对象中的每个项目并将其存储在不同的变量中来从地图对象获取列表。

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']

You can try getting a list from the map object by just iterating each item in the object and store it in a different variable.

a = map(chr, [66, 53, 0, 94])
b = [item for item in a]
print(b)
>>>['B', '5', '\x00', '^']
断念 2024-08-08 22:37:16

另一种选择是创建一个快捷方式,返回一个列表:

from functools import reduce
_compose = lambda f, g: lambda *args: f(g(*args))
lmap = reduce(_compose, (list, map))

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

Another option is to create a shortcut, returning a list:

from functools import reduce
_compose = lambda f, g: lambda *args: f(g(*args))
lmap = reduce(_compose, (list, map))

>>> lmap(chr, [66, 53, 0, 94])
['B', '5', '\x00', '^']
久而酒知 2024-08-08 22:37:16

在 pyton3.X 中执行此操作的最佳方法

只需单行即可执行此操作

#Devil
input_list = [66, 53, 0, 94]
out = [chr(x) for x in input_list]
print(out)

# you will get the desire output in out list
# ['B', '5', '\x00', '^']

#------------------------------
#To retrieve your list use 'ord'

original_list = [ord(x) for x in out]
print(original_list )
#[66, 53, 0, 94]

Best Way to do this in pyton3.X

Simply you can do this in single line

#Devil
input_list = [66, 53, 0, 94]
out = [chr(x) for x in input_list]
print(out)

# you will get the desire output in out list
# ['B', '5', '\x00', '^']

#------------------------------
#To retrieve your list use 'ord'

original_list = [ord(x) for x in out]
print(original_list )
#[66, 53, 0, 94]
泡沫很甜 2024-08-08 22:37:16
list(map(chr, [66, 53, 0, 94]))

map(func, *iterables) -->; 地图对象
创建一个迭代器,使用以下参数计算函数
每个可迭代对象。 当最短的迭代耗尽时停止。

“创建一个迭代器”

意味着它将返回一个迭代器。

“使用每个可迭代对象的参数计算函数”

意味着迭代器的 next() 函数将采用每个可迭代对象的一个​​值,并将它们中的每一个传递给函数的一个位置参数。

因此,您可以从 map() 函数获取一个迭代器,然后将其传递给 list() 内置函数或使用列表推导式。

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

map(func, *iterables) --> map object
Make an iterator that computes the function using arguments from
each of the iterables. Stops when the shortest iterable is exhausted.

"Make an iterator"

means it will return an iterator.

"that computes the function using arguments from each of the iterables"

means that the next() function of the iterator will take one value of each iterables and pass each of them to one positional parameter of the function.

So you get an iterator from the map() funtion and jsut pass it to the list() builtin function or use list comprehensions.

玩世 2024-08-08 22:37:16

使用 python 中的列表理解和基本地图函数实用程序,也可以做到这一点:

chi = [x for x in map(chr,[66,53,0,94])]

Using list comprehension in python and basic map function utility, one can do this also:

chi = [x for x in map(chr,[66,53,0,94])]

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文