4 ms·
It can be made a little neater, show off a little more of Python and be more versatile by replacing range(10) with count() from the iterator module [http://docs
by dood 19y ago
It can be made a little neater, show off a little more of Python and be more versatile by replacing range(10) with count() from the iterator module [http://docs.python.org/lib/itertools-functions.html http://docs.python.org/lib/itertools-functions.html]
from itertools import count
words = "zero one two three four five six seven eight nine".split()
word_to_number = dict(zip(words, count()))
[http://codepad.org/naCDzno7 http://codepad.org/naCDzno7]
- BrandonM 19y agoI like itertools as much as the next programmer (although a large subset of it will be subsumed when Python3k switches to iterators on operations like map and zip), but I feel like using an imported module to (apparently) produce a list of numbers might actually give the wrong idea about Python. In several other languages, you can't even write to standard output without importing a module or five, whereas in Python, you can get a lot done without even touching the standard library (although you will likely want to rather quickly). Seeing an import statement at the top might give the Python newbie the idea that core Python doesn't have "basic" functionality. I think a good later lesson would be to explain how iterators and the standard library works and then revisit this code to make it look like your example, but in the beginning, I think range(10) would be simpler and would better serve the purpose of the lesson. Even in this case, xrange (at least in Python 2.x) is obviously the better choice, but introducing that complexity at this point doesn't gain much, in my opinion.
- eru 19y agoWon't range behave like xrange soon anyway?
- jacobolus 19y agoOr just: words = "zero one two three four five six seven eight nine ten".split() word_to_number = dict((j,i) for i,j in enumerate(words))