Sorting a list
Peter Otten
__peter__ at web.de
Sun Apr 3 15:31:05 EDT 2016
DFS wrote:
> cntText = 60
> cntBool = 20
> cntNbrs = 30
> cntDate = 20
> cntBins = 20
>
> strText = " text: "
> strBool = " boolean: "
> strNbrs = " numeric: "
> strDate = " date-time:"
> strBins = " binary: "
>
> colCounts = [(cntText,strText) , (cntBool,strBool), (cntNbrs,strNbrs) ,
> (cntDate,strDate) , (cntBins,strBins)]
>
> # sort by alpha, then by column type count descending
> colCounts.sort(key=lambda x: x[1])
> colCounts.sort(key=lambda x: x[0], reverse=True)
> for key in colCounts: print key[1], key[0]]
>
> -------------------------------------------------
>
> Output (which is exactly what I want):
>
> text: 60
> numeric: 30
> binary: 20
> boolean: 20
> date-time: 20
>
> -------------------------------------------------
>
>
> But, is there a 1-line way to sort and print?
Yes, but I would not recommend it. You can replace the sort() method
invocations with nested calls of sorted() and instead of
for item in items:
print convert_to_str(item)
use
print "\n".join(convert_to_str(item) for item in items)
Putting it together:
>>> from operator import itemgetter as get
>>> print "\n".join("{1} {0}".format(*p) for p in sorted(
... sorted(colCounts, key=get(1)), key=get(0), reverse=True))
text: 60
numeric: 30
binary: 20
boolean: 20
date-time: 20
You could also cheat and use
lambda v: (-v[0], v[1])
and a single sorted().
More information about the Python-list
mailing list