Why can't I sort this list?

statlist = [('abc',5,1), ('bzs',66,1), ... ]
sorted(statlist, key=lambda x: int(x[1]))

I want to sort it by integer, smallest. In this case, 5 and 66. But it does not seem to work.

+3
source share
8 answers

The function sortedreturns a new list, so you will need to assign the results of the function as follows:

new_list = sorted(statlist, key=lambda x: int(x[1])) 
+7
source

Use the method .sortto sort by location:

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist.sort(key=lambda x: int(x[1]))

If you want to use sorted, reassign the variable:

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=lambda x: int(x[1]))

To sort in descending order use reverse:

statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=lambda x: int(x[1]), reverse=True)

Then you better use itemgetterinstead lambda:

import operator
statlist = [('abc',5,1), ('bzs',66,1), ... ]
statlist = sorted(statlist, key=operator.itemgetter(1), reverse=True)
+7
source

, .sort

>>> x.sort(key=lambda x:x[1],reverse=True)
>>> x
[('bzs', 66, 1), ('abc', 5, 1)]
>>>
+3

inplace

statlist.sort(key=lambda x: x[1])

otherlist = sorted( statlist, key=lambda x: x[1] )
+3
from operator import itemgetter
statlist = [('abc',5,1), ('bzs',66,1), ... ]

# statlist.sort modifiest the statlist, sorted returns a new one
# reverse puts the largest items to the front
statlist.sort(key=itemgetter(1), reverse=True)
+2

alex , sorted() " ":

" ", .

, ... .

:

>>> alist = [3, 2, 1]; x = alist.sort(); print x; print alist
None
[1, 2, 3]
>>> alist = [3, 2, 1]; x = sorted(alist); print x; print alist
[1, 2, 3]
[3, 2, 1]

: , . reverse reversed.

+1
>>> s = [('xyz', 8, 1), ('abc',5,1), ('bzs',66,1) ]
>>> s = sorted(s, key=lambda x: int(x[1]))
>>> s.reverse()
>>> print s
[('bzs', 66, 1), ('xyz', 8, 1), ('abc', 5, 1)]
0

Hey, when ever I store something in an array, I am not inclined to worry about the order, and then in the end I use sorted(), for example, like this statlist = sorted(statlist)one and if you want it to be the smallest statlist = sorted(statlist, reverse = True)This is an easy way to get the largest of the smallest !

Sample code where I used this (just extract)

    while i <= math.sqrt(intnum):
        if (intnum % i) == 0:
            numbers.insert(0,i)
            numbers.insert(0,int(intnum/i))
            print(i,":", int(intnum/i))
        i += 1
    numbers = sorted(numbers, reverse = True)
0
source

Source: https://habr.com/ru/post/1724217/


All Articles