Posts Tagged ‘Python’
A Python sort trick
By chys on October 23rd, 2009>>> a = [12,14,133,130,176,25,54,79,127] >>> b = sorted(range(len(a)),key=a.__getitem__) >>> b [0, 1, 5, 6, 7, 8, 3, 2, 4] >>> map(a.__getitem__,b) [12, 14, 25, 54, 79, 127, 130, 133, 176]
b is the so called sort index.
Reference
http://www.newsmth.net/bbscon.php?bid=284&id=59819
Tags: Python
__cmp__ should be reintroduced to Python
By chys on August 11th, 2009A lot of people think this decision to drop __cmp__ from Python sucks. (1 2)
The cmp argument is also dropped from list.sort and sorted. Some people explain that some programmers used to use cmp when it is more convenient and efficient to use key. By dropping cmp, poor programmers are forced to use key. On the other hand, almost all comparators found in practice are actually based on some kind of key function.
Well, theoretically this probably is true: something.sort(key=locale.strxfrm) is better than something.sort(cmp=locale.strcoll).
BUT, what can I do if I only have a third-party comparator?
I have a Python script where I use vercmp, provided in the source of Gentoo Portage, to sort a list of Gentoo packages. No corresponding verkey is provided. So now, in Python 3, I have to either write a verkey myself, or use the following ugly and inefficient workaround:
class VerKey:
def __init__(self,str):
self.str = str
def __lt__(self,other):
return vercmp(self.str, other.str) < 0
versions.sort (key = VerKey)
Tags: Python
Python string formatting: tuples
By chys on February 17th, 2009Python generally expects the parameter list following the format operator (%) to be a tuple (sometimes a dictionary) consisting of all the parameters.
You can also put the tuple in another tuple, and it’s still accepted. Put the tuple consisting of the tuple in another tuple, and it is still accepted. Therefore the following three lines are equivalent:
'%d,%d' % (2,3)
'%d,%d' % ((2,3))
'%d,%d' % (((2,3)))
You can add more brackets if you like to.
A sad consequence of this is that, if the object you want to format is ITSELF a tuple, you’re really going to confuse Python.
Let A=(2,3) and try to format it using the "%r" format specifier:
print 'A=%r' % A
Errorprint 'A=%r' % (A)
Errorprint 'A=%s' % (repr(A))
Outputs “A=(2,3)“, of course. If this still refuses to work, I’m really going to throw Python into the trashcan immediately…print 'A=%(0)r' % {'0':A}
Outputs “A=(2,3)“. This also works, but isn’t it annoying to use the unnecessary dictionary?
If A is anything else (a list, a dictionary, an integer, a string, an object,…), all four statements work as expected.
If the parameter list has more than just one tuple, it also works very well.
My question is that: is it really necessary to support codes like this? Who uses it?
print '%d, %d' % (((((((2,3)))))))
Update: Information in this post is inaccurate
Tags: Python
