PROJET AUTOBLOG


Shaarli - Les discussions de Shaarli

Archivé

Site original : Shaarli - Les discussions de Shaarli

⇐ retour index

[Python 3 FIX] 30 Python Language Features and Tricks You May Not Know About: Mapping objects to unique counting numbers (collections.defaultdict)

lundi 19 mai 2014 à 09:30
JeromeJ, le 19/05/2014 à 09:30
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()))
(Permalink)