开发者

Sort float in list of lists in Python?

开发者 https://www.devze.com 2023-04-11 13:43 出处:网络
I am trying to开发者_StackOverflow社区 sort a nested list structure based on the last values of each nested lists. My list looks like this:

I am trying to开发者_StackOverflow社区 sort a nested list structure based on the last values of each nested lists. My list looks like this:

li = [['a1', 1, 1.56], ['b3', '6', 9.28], ['c2', 1, 6.25]...]

The output I would like is:

['b3', '6', 9.28]
['c2', 1, 6.25]
['a1', 1, 1.56]

I have tried a few solutions that haven't worked using itemgetter like this:

 rank_list = [i.sort(key=itemgetter(2)) for i in li]

What am I doing wrong? Is there a better way to sort nested lists? I get an AttributeError: 'str' object has no attribute 'sort'. Thanks for the help.


You're close with one of your approaches, but what you actually want is this:

li.sort(key = itemgetter(2), reverse = True)


rank_list = sorted(li, key=itemgetter(2))


Strings can't be sorted, that's what AttributeError: 'str' object has no attribute 'sort' want to tell you.

You want to sort the list li

 rank_list = sorted(li, key=itemgetter(2)) # to obtain a sorted copy of li
 # or just sort in place:
 li.sort(key=itemgetter(2))

Whatever you do it's not what you posted though:

>>> rank_list = [i.sort(key=itemgetter(2)) for i in li]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: string index out of range


Let's clarify our thinking about the problem.

[i.sort(key=itemgetter(2)) for i in li]

This means "take each sub-list and sort its elements (the list and the two strings), using item 2 of each as a key; accumulate a list of the return values from those operations". The elements of your sub-lists are ints and strings; ints aren't sequences at all (so you can't get an item from them), and some of your strings are too short (when I try your example, I don't get the error you cite, but instead "IndexError: string index out of range", as expected). Even if this did work, you would just get a list of None values, because .sort on a list sorts the list in-place and returns None.

What you want is "give me the sorted-by-item-2-of-each-element version of this list-of-lists". That is sorted(li, key=itemgetter(2)). The list-of-lists is what you're sorting, so that's what you pass to a sort function. You want the sort to give a new value and not affect things in-place, so you use the free function sorted instead.

0

精彩评论

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