开发者

Sorting list of lists with mixed numerical values

Scenario: List containing 'rows' of list records with a variety of values

Problem: List.sort doesn't take the numeric values into consideration so values end up all over the place

i.e 9 is appearing in the开发者_JAVA技巧 list after 80

I've tried using

list.sort(key=operator.itemgetter[index])

and doing a

list.sort(lambda x,y:int(x[index])<int(y[index])) 

to no avail.


Use the converted number as the key.

L.sort(key=lambda x: int(x[index]))


You're on the right track, but operator.itemgetter is a function, so the syntax is:

list.sort(key=operator.itemgetter(index))

Or alternatively, use a lambda:

list.sort(key=lambda x: x[index])

The key parameter is the way to go, the cmp parameter has been removed in Python 3. If you want to use it anyway, you should use the cmp() built-in function to implement your comparator:

list.sort(cmp=lambda x, y: cmp(x[index], y[index]))

See also: http://wiki.python.org/moin/HowTo/Sorting/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜