开发者

Sorting by values in a sublist in python

My list contains a number of elements in this format

(23, (12,16,42))

my rudimentary sort right now will sort by the first value in the sublist by default.

value = sorted(list, key=itemgetter(1))

I want to use a second level sort option as described http:开发者_开发知识库//wiki.python.org/moin/HowTo/Sorting/

sorted(student_tuples, key=itemgetter(1,2))

So is there an address for each of the items in the sublist? I've tried to find some bracket or colon notation and just haven't spotted it yet I assume.

Example unsorted list

(0, (81.0, 5.0, 83.0)), (1, (81.0, 1.0, 26.0)), (2, (80.0, 1.0, 44.0)), 

the output would be similar to

(2, (80.0, 1.0, 44.0)), (1, (81.0, 1.0, 26.0)), (0, (81.0, 5.0, 83.0))

(w, (x,y,z))

so the first sort is on x. If there are multiple x values, it sorts them by y


Define it yourself:

sorted(list, key=lambda item: item[0][1])
# or whatever other sort of indexing you want

In your case, the indexing you want is:

sorted(list, key=lambda item: (item[1][0], item[1][1]))

since comparing tuples works by comparing elements pairwise. key is any callable that transforms the items into a thing that can be compared directly in order to get the desired comparison results.


The general way to sort by multiple properties, is to have a key function that returns a tuple. This works because Python sorts tuples from left to right, so it sounds like you are trying to do this

>>> L=(0, (81.0, 5.0, 83.0)), (1, (81.0, 1.0, 26.0)), (2, (80.0, 1.0, 44.0)),
>>> sorted(L, key=lambda x:(x[1][0],x[1][1]))
[(2, (80.0, 1.0, 44.0)), (1, (81.0, 1.0, 26.0)), (0, (81.0, 5.0, 83.0))]

Since the order of the fields you want to sort by is the same as the order in the tuple, you can simplify to this

>>> sorted(L, key=lambda x:x[1])
[(2, (80.0, 1.0, 44.0)), (1, (81.0, 1.0, 26.0)), (0, (81.0, 5.0, 83.0))]

Which gets you back to simply

>>> sorted(L, key=itemgetter(1))
[(2, (80.0, 1.0, 44.0)), (1, (81.0, 1.0, 26.0)), (0, (81.0, 5.0, 83.0))]

But hopefully now you can see why this does sort on the elements in the order you desire


>>> a = [23, [5, 6, 7]]
>>> a[1][0]
5

The sublist is an item, so you use one set of brackets to get that sublist, and then another to index into the sublist.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜