I have a problem that I want to solve with itertools.imap(). However, after I imported itertools in IDLE shell and called itertools.imap(), the IDLE shell told me that itertools doesn't have attribute imap. What's going wrong?
>>> import itertools
>>> dir(itertools)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', '_grouper', '_tee', '_tee_dataobject', 'accumulate', 'chain', 'combinations', 'combinations_with_replacement', 'compress', 'count', 'cycle', 'dropwhile', 'filterfalse', 'groupby', 'islice', 'permutations', 'product', 'repeat', 'starmap', 'takewhile', 'tee', 'zip_longest']
>>> itertools.imap()
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
itertools.imap()
AttributeError: 'module' object has no attribute 'imap'
itertools.imap()
is in Python 2, but not in Python 3.
Actually, that function was moved to just the map
function in Python 3 and if you want to use the old Python 2 map, you must use list(map())
.
If you want something that works in both Python 3 and Python 2, you can do something like:
try:
from itertools import imap
except ImportError:
# Python 3...
imap=map
You are using Python 3, therefore there is no imap
function in itertools
module. It was removed, because global function map
now returns iterators.
How about this?
imap = lambda *args, **kwargs: list(map(*args, **kwargs))
In fact!! :)
import itertools
itertools.imap = lambda *args, **kwargs: list(map(*args, **kwargs))
I like the python-future
idoms for universal Python 2/3 code, like this:
# Works in both Python 2 and 3:
from builtins import map
You then have to refactor your code to use map
everywhere you were using imap
before:
myiter = map(func, myoldlist)
# `myiter` now has the correct type and is interchangeable with `imap`
assert isinstance(myiter, iter)
You do need to install future for this to work on both 2 and 3:
pip install future
You can use the 2to3 script (https://docs.python.org/2/library/2to3.html) which is part of every Python installation to translate your program or whole projects from Python 2 to Python 3.
python <path_to_python_installation>\Tools\scripts\2to3.py -w <your_file>.py
(-w option writes modifications to file, a backup is stored)