I am having difficulty sorting a list of tuples. I would like to sort by the length of a string in the list.
For example:
l = [(99,'bbc', 121),(33,'abcd', 231),(44,'zb', 148), (23,'abcde',221)]
if I sort by element 1:
l.sort(key=itemgetter(1), reverse=True)
This will sort on the alphabetical ranking of the strings, not the length. I would prefer to sort in-place and reverse sort, with longest string first.
I can use a lambda and cmp,
l.sort(lambda x,y: cmp(len(x[1]), len(y[1])), reverse=True)
but is there a more elegant, or pythonic way using key and/or itemgetter?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…