by ims · 12y ago · 0 comments
The nice thing about a Counter is that it will take a collection of things and... count them:
>>> from random import randrange
>>> from collections import Counter
>>> mycounter = Counter(randrange(10) for _ in range(100))
>>> mycounter
Counter({1: 15, 5: 14, 3: 11, 4: 11, 6: 11, 7: 11, 9: 8, 8: 7, 0: 6, 2: 6})
Docs: https://docs.python.org/2/library/collections.html#counter-o..._ in python is commonly used as a variable name for values you want to throw away. For example, let's say you have a log file split on newlines, with records like this:
logline = "127.0.0.1 localhost.example.com GET /some/url 404 12413"
You want to get all the URLs that are 404s, but you don't care about who requested them, etc. You could do this: _, _, _, url, returncode, _ = logline.split(' ')
There's no special behaviour for _ in this case; in fact, normally in the interactive interpreter it's used to store the result of the last evaluated line, like so: >>> SomeModel.objects.all()
[SomeModel(…), SomeModel(…), SomeModel(…), …]
>>> d = _
>>> print d
[SomeModel(…), SomeModel(…), SomeModel(…), …]
Which I think is basically the same behaviour; you run some code, you don't assign it, so the interpreter dumps it into _ and goes on about its day.