简体   繁体   中英

Sorting a list with sublists, based on whether the sublist has a designated string

I want to sort a list in a way that the elements (sublists) which have a certain string (of my choosing) come first. I'd like to do this with the key parameter in Python's sort() method.

For example, if I have

Input

l1 = [["hello", 1, 65, 331],["goodbye", 653, 43, 9], ["example", 22, 123, 92]]

I'd like to use l1.sort() to sort the list in a way that, given "example" as the parameter, sorts the list like this:

Output

[["example", 22, 123, 92], ["hello", 1, 65, 331], ["goodbye", 653, 43, 9]] .

Is this possible?

Say you want goodbye to come first, you could do:

l1 = [["hello", 1, 65, 331],["goodbye", 653, 43, 9], ["example", 22, 123, 92]]

s = 'goodbye'
sorted(l1, key=lambda x: x[0]!=s)
# [['goodbye', 653, 43, 9], ['hello', 1, 65, 331], ['example', 22, 123, 92]]

For a detailed exaplanation on how the above works, check this other answer

you can use a lambda expression to check if the keyword is in the sublist, this will return a boolean truth value for each expression in which False will be ordered before True , so we also apply reverse so that those that were True come first. it will maintain the order of the sub list after ordering by True and False . So those sublists with the same truth value will stay in the order they were in.

l1 = [["hello", 1, 65, 331],["goodbye", 653, 43, 9], ["example", 22, 123, 92]]
keyword = "example"
print(l1)
l1.sort(key=lambda sublist: keyword in sublist, reverse=True)
print(l1)

OUTPUT

[['hello', 1, 65, 331], ['goodbye', 653, 43, 9], ['example', 22, 123, 92]]
[['example', 22, 123, 92], ['hello', 1, 65, 331], ['goodbye', 653, 43, 9]]

Here's the code. Excuse me for putting it this long but it serves the purpose :)

import operator
def sortfunction(parameter,list):
    tmplist1 = []
    tmplist2 = []
    for elem in list:
        if elem[0] == parameter:
            tmplist1 = elem
        else:
            tmplist2.append(elem)
    sorted_temp = sorted(tmplist2, key=operator.itemgetter(1),reverse=True)
    final_list = tmplist1 + sorted_temp
    return final_list

#Call the function:
sortfunction("example",l1)

Output:

['example', 22, 123, 92, ['goodbye', 653, 43, 9], ['hello', 1, 65, 331]]

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