Quantcast
Channel: Active questions tagged python - Stack Overflow
Viewing all articles
Browse latest Browse all 23131

Trying to sort a list of lists in a "special" way...I think

$
0
0

I have a list of lists that looks something like this:

test_list = [['V1'],['V3','V2'],['V3'],['V2','V1'],['V1','V2']]

And I want it to end up like this:

sorted_list = [['V1'],['V1','V2'],['V2','V1'],['V3','V2'],['V3']]

(Note the 'V's are an artifact of my use case, but are probably irrelevant because they are a constant prefix.)

The list may have any number of elements, but will always have exactly 2 single-item lists (the "ends", always containing the lowest and highest numbers in the list). The rest are 2-item lists that will go in between. Those need to be sorted by their first element.

It seems I can do this with "brute force", separating the single and double item lists, sorting both, then inserting the doubles back into the singles, like this:

sorted_list = sorted([x for x in test_list if len(x) == 1])doubles_list = sorted([x for x in test_list if len(x) == 2])sorted_list[1:1] = doubles_list

But I keep thinking there's a more elegant or compact way to do this that I just can't see. (And I've also been looking at it so long I can't tell if that's really a robust, bulletproof way to do it.)

Any insight appreciated!


Viewing all articles
Browse latest Browse all 23131

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>