Home > other >  Python: Move specific lists within list, based on an element, at the end
Python: Move specific lists within list, based on an element, at the end

Time:10-28

I have a list which contains other lists. Each element of this list contains 5 elements, like so:

requests = [['abc', 'def', '[email protected]', 'GROUP1', '000'],
           ['ghi', 'jkl', 'ghi,[email protected]', 'GROUP4', '111'],
           ['mno', 'pqr', '[email protected]', 'GROUP4', '222'],
           ['stu', 'vxy', '[email protected]', 'GROUP2', '333'],
           ['123', '456', '[email protected]', 'GROUP4', '444'],
           ['A12', 'B34', '[email protected]', 'GROUP3', '555']]

I would like to sort this list, in such a way that each list that contains an element equal to GROUP4, will be placed at the end of the list. So, the output would look like this:

requests = [['abc', 'def', '[email protected]', 'GROUP1', '000'],
           ['stu', 'vxy', '[email protected]', 'GROUP2', '333'],
           ['A12', 'B34', '[email protected]', 'GROUP3', '555'],
           ['ghi', 'jkl', 'ghi,[email protected]', 'GROUP4', '111'],
           ['mno', 'pqr', '[email protected]', 'GROUP4', '222'],
           ['123', '456', '[email protected]', 'GROUP4', '444'],]

I managed to sort them based on that specific element using:

requests.sort(key=lambda x: x[3])

But this just sorts them alphabetically, based on the 4th element. This won't work if a GROUP5 or GROUP6 is present, as those 2 will be the last elements.

Any ideas on how to do this?

Thank you very much!

CodePudding user response:

You can change the lambda to check if the last character in 'GROUP' is 4

requests.sort(key=lambda x: x[3][-1] == '4')

If you want to sort the rest of the list as well use tuple in the lambda with two conditions

requests.sort(key=lambda x: (x[3][-1] == '4', x[3]))

CodePudding user response:

Move lists with GROUP4 at index [3] to the end by sorting by boolean.

requests.sort(key=lambda el: el[3] == "GROUP4")

CodePudding user response:

you can also use list comprehension:

firstList = [a for a in requests if a[3] != 'GROUP4']
secondList = [a for a in requests if a[3] == 'GROUP4']
firstList.extend(secondList)
  • Related