In Python 3.x, the map() function returns an iterator by default instead of a list. This can be inconvenient if you want to use the mapped elements directly.
A common task is to convert a list of integers into their hexadecimal representations. In Python 2.6, this was straightforward using the map() function, as shown below:
# Python 2.6 hex_list = map(chr, [66, 53, 0, 94]) # Return a list of hex characters
However, in Python 3.1, the above code returns a map object:
# Python 3.1 hex_map = map(chr, [66, 53, 0, 94]) # Return a map object
To retrieve the actual list of mapped elements in Python 3.x, you can use the list() function to convert the map object into a list:
hex_list = list(map(chr, [66, 53, 0, 94]))
An alternative approach to mapping a list of integers to their hexadecimal representations is to use a list comprehension, as follows:
hex_list = [chr(n) for n in [66, 53, 0, 94]]
This approach eliminates the need to use the map() function and creates a list directly.
Note that you can still iterate over a map object in Python 3.x without converting it to a list first:
for ch in map(chr, [65, 66, 67, 68]): print(ch) # Prints "ABCD"
The above is the detailed content of How to Convert Python 3's `map` Object to a List?. For more information, please follow other related articles on the PHP Chinese website!