简体   繁体   中英

How can I sort list by second element without using lambda?

def rearrangelist(list):
    lst = input["list"]
    lst = ['list'[0]:1,'list'[1]:0,'list'[2]:3];
    print (sorted(list))

How can I make this work without using lambda, once I basically want the list elements to be rearrange according to the number that each list element gets defined, per example:

list = [john, peter, olive]
john[2], peter [1] and olive[0]

And I want this to be sorted according to the number printing this:

olive, peter, john

Can´t use "Zip()" function

The easiest solution is to use the operator.itemgetter function

from operator import itemgetter

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

By the way, list is a terrible name for a variable, as it will shadow the list type.

sorted(iterable[, cmp[, key[, reverse]]]) Return a new sorted list from the items in iterable.

The optional arguments cmp, key, and reverse have the same meaning as those for the list.sort() method.

key specifies a function of one argument that is used to extract a comparison key from each list element: key=str.lower. The default value is None (compare the elements directly).

key is what you need. Supply it a function that will return a comparison key

def SortBySecondElement(Element):
    return Element[1]

Call sorted method this way

sorted(list, key=SortBySecondElement)

I hope that is what you want.

You can use the decorate-sort-undecorate idiom :

>>> names = ['john', 'peter', 'olive']
>>> order = [2, 1, 0]

>>> decorated = zip(order, names)
>>> decorated
[(2, 'john'), (1, 'peter'), (0, 'olive')]

>>> sorted_decorated = sorted(decorated)
>>> sorted_decorated
[(0, 'olive'), (1, 'peter'), (2, 'john')]

>>> undecorated = zip(*sorted_decorated)[1]
>>> undecorated
('olive', 'peter', 'john')

If you can't use zip:

>>> decorated = [(order[index], names[index]) for index in range(len(order))]

And:

>>> undecorated = [value[1] for value in decorated_sorted]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM