2015-05-16 12 views
17

Ho un problema che voglio risolvere con itertools.imap(). Tuttavia, dopo aver importato itertools nella shell IDLE e chiamato itertools.imap(), la shell IDLE mi ha detto che itertools non ha l'attributo imap. Cosa c'è che non va?Non riesco a trovare 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

Può essere interessante anche per dare un'occhiata a [itertools.starmap] (https://docs.python.org/3.6/library/itertools.html#itertools.starmap) in pyhton3. –

risposta

19

itertools.imap() è in Python 2, ma non in Python 3.

In realtà, tale funzione è stata spostata alla sola funzione di map in Python 3 e se si desidera utilizzare la vecchia mappa Python 2, è necessario utilizzare list(map()) .

+1

grazie amico, stavo anche cercando di importare accumulare ma non funzionava. Il problema era python2.x, ora passato a python3.X inizia a funzionare – Athar

6

Si sta utilizzando Python 3, quindi non v'è alcuna imap funzione nel modulo itertools. È stato rimosso, poiché la funzione globale map restituisce ora gli iteratori.

8

Se si desidera qualcosa che funziona sia in Python 3 e Python 2, si può fare qualcosa di simile:

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

ne dici di questo?

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

Infatti !! :)

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