148 points · by carldz9 · 16y ago · 40 comments
>>> {s: len(s) for s in ["one", "two", "three"]
{"one": 3, "two": 3, "three": 5} (defn map-comprehension [f sequence]
(reduce #(assoc %1 %2 (f %2)) {} sequence))
usage: user> (map-comprehension count ["one" "two" "three"])
{"three" 5, "two" 3, "one" 3} >>> dict((s, len(s)) for s in ["one", "two", "three"])
{'three': 5, 'two': 3, 'one': 3} (True + True) == 2
(sorry, one of my few pet-peeves after it bit me one time) >>> issubclass(bool, int)
True
>>> isinstance(True, int)
True
>>> int(True)
1
>>> int(False)
0
>>> True == 1
True
>>> False == 0
TrueYou can check if two out of three are true with
(bool1 + bool2 + bool3) >= 2
You can do
count_negatives = sum(number < 0 for number in numbers)
It's just like Duck Typing- you're trading the need to explicitly specify an interface for the potential dangers of letting your interpreter "know what you mean".
If this is frequently a problem, well... there are a lot of strongly-typed languages out there waiting for you to give them a try.
So no, it does not have a use :)
True + True == False
might be a common interpretation.Yes, I have heard of "batteries included" and all, but after working with Python for a year I still felt that the size of its library has been "hidden" from general programming public.
I love Python.
Runs a local SMTP server on port 2525. Very useful for debugging.
Now that's a feature I wish I knew about sooner. I've been using:
for item in a:
print a.index(item), item
which has always felt kludgy. import itertools
for (index, item) in zip(itertools.count(0), "hallo"):
print index, item
Itertools is worth checking out for other goodies, too. for i in range(len(a)):
print i, a[i](Ok, I didn't know about re.DEBUG)
EDIT: I'm not claiming this link is worthless. But I'd call it "great features of python" or simply "features of python"