Retrieving Mapped Lists in Python 3.x: map() as an Iterator
In Python 3.x, the map() function returns an iterator instead of a list. This change was implemented to improve memory efficiency and optimize performance. However, it poses a challenge if you need to retrieve the mapped values as a list for further processing.
Solution: Converting the Iterator to a List
To retrieve the mapped values as a list, use the list() function to convert the iterator returned by map():
mapped_list = list(map(chr, [66, 53, 0, 94]))
This code will return a list containing the mapped characters: ['B', '5', '\x00', '^'].
Alternative: Using a List Comprehension
A more concise way to convert a list into a list of mapped values is to use a list comprehension:
mapped_list = [chr(c) for c in [66, 53, 0, 94]]
This expression produces the same result as the map() example above.
Iterating Over the Map Object Directly
In certain scenarios, you may not need to convert the map object to a list. You can iterate over the map object directly using a for loop:
for c in map(chr, [65, 66, 67, 68]): print(c)
This code will print the characters "ABCD" without creating an unnecessary list.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3