614 shaares
AttributeError: 'itertools.count' object has no attribute 'next'
Arf …
Le code suivant ne fonctionne donc plus en Python 3 :
>>> import itertools, collections
>>> value_to_numeric_map = collections.defaultdict(itertools.count().next)
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
>>> value_to_numeric_map['c']
2
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
La première solution venant à l'esprit serait d'avoir à instancier une variable :
>>> c = itertools.count()
>>> value_to_numeric_map = collections.defaultdict(lambda a: next(c))
Et ça fonctionne très bien.
Mais personnellement, je préfère lorsque ça reste one-line, donc voici une alternative one-line :
J'utilise lambda pour créer une encapsulation (closure).
value_to_numeric_map = collections.defaultdict((lambda c: (lambda: next(c)))(itertools.count()))
Arf …
Le code suivant ne fonctionne donc plus en Python 3 :
>>> import itertools, collections
>>> value_to_numeric_map = collections.defaultdict(itertools.count().next)
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
>>> value_to_numeric_map['c']
2
>>> value_to_numeric_map['a']
0
>>> value_to_numeric_map['b']
1
La première solution venant à l'esprit serait d'avoir à instancier une variable :
>>> c = itertools.count()
>>> value_to_numeric_map = collections.defaultdict(lambda a: next(c))
Et ça fonctionne très bien.
Mais personnellement, je préfère lorsque ça reste one-line, donc voici une alternative one-line :
J'utilise lambda pour créer une encapsulation (closure).
value_to_numeric_map = collections.defaultdict((lambda c: (lambda: next(c)))(itertools.count()))