2015-05-16 11 views
17

Ich habe ein Problem, das ich mit itertools.imap() lösen wollen. Nachdem ich jedoch itertools in die IDLE-Shell importiert und itertools.imap() aufgerufen habe, hat mir die IDLE-Shell gesagt, dass iertools kein Attribut imap hat. Was läuft falsch?Ich kann nicht finden imap() in itertools in Python

>>> 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' 
+0

Es kann auch einen Blick nehmen auf [itertools.starmap] (https://docs.python.org/3.6/library/itertools.html#itertools.starmap) in pyhton3 interessant sein. –

Antwort

19

itertools.imap() ist in Python 2, aber nicht in Python 3.

Eigentlich wurde diese Funktion nur die map Funktion in Python 3 bewegt, und wenn Sie die alte Python 2 Karte verwenden möchten, müssen Sie list(map()) verwenden .

+1

danke Kumpel, ich habe auch versucht, zu akkumulieren, aber hat nicht funktioniert. Das Problem war python2.x, jetzt zu python3.x gewechselt, es beginnt zu arbeiten – Athar

6

Sie Python 3 verwenden, daher gibt es keine imap Funktion in itertools Modul. Es wurde entfernt, da die globale Funktion map jetzt Iteratoren zurückgibt.

8

Wenn Sie wollen etwas, das sowohl in Python 3 und Python funktioniert 2, können Sie so etwas wie:

try: 
    from itertools import imap 
except ImportError: 
    # Python 3... 
    imap=map 
0

Wie wäre das?

imap = lambda *args, **kwargs: list(map(*args, **kwargs)) 

In der Tat! :)

import itertools 
itertools.imap = lambda *args, **kwargs: list(map(*args, **kwargs))