I want to sort naturally, no matter the value, I have found code to do this elsewhere on stack, I just can't incorporate it into what I have,
here's what I have, it sorts the order of the main sublists by the index which the only '0' is in, top right, "sublist[1][3]"
sheet_lists = [[1, ['', '', '', '0']],
[2, ['', '', '', '1']],
[3, ['', '', '', '2']],
[4, ['', '', '', '3']],
[5, ['', '', '', '4']],
[6, ['', '', '', '5']],
[7, ['', '', '', '6']],
[8, ['', '', '', '7']],
[9, ['', '', '', '8']],
[10, ['', '', '', '9']],
[11, ['', '', '', '10']],
[12, ['', '', '', '11']],
[13, ['', '', '', '12']],
[14, ['', '', '', '13']],
[15, ['', '', '', '14']],
[16, ['', '', '', '15']],
[17, ['', '', '', '16']],
[18, ['', '', '', '17']]]
sheet_lists.sort(key=lambda lst: lst[1][3], reverse=True)
for l in sheet_lists:
print (l)
The output this produces is:
[10, ['', '', '', '9']]
[9, ['', '', '', '8']]
[8, ['', '', '', '7']]
[7, ['', '', '', '6']]
[6, ['', '', '', '5']]
[5, ['', '', '', '4']]
[4, ['', '', '', '3']]
[3, ['', '', '', '2']]
[18, ['', '', '', '17']]
[17, ['', '', '', '16']]
[16, ['', '', '', '15']]
[15, ['', '', '', '14']]
[14, ['', '', '', '13']]
[13, ['', '', '', '12']]
[12, ['', '', '', '11']]
[11, ['', '', '', '10']]
[2, ['', '', '', '1']]
[1, ['', '', '', '0']]
I expect:
[18, ['', '', '', '17']]
[17, ['', '', '', '16']]
[16, ['', '', '', '15']]
[15, ['', '', '', '14']]
[14, ['', '', '', '13']]
[13, ['', '', '', '12']]
[12, ['', '', '', '11']]
[11, ['', '', '', '10']]
[10, ['', '', '', '9']]
[9, ['', '', '', '8']]
[8, ['', '', '', '7']]
[7, ['', '', '', '6']]
[6, ['', '', '', '5']]
[5, ['', '', '', '4']]
[4, ['', '', '', '3']]
[3, ['', '', '', '2']]
[2, ['', '', '', '1']]
[1, ['', '', '', '0']]
As you can see, this doesn't sort properly and NOTE: I don't want to simply convert the values to INT or FLOAT before sorting. This is because I anticipate values which include letters or possibly symbols.
Here's the code for naturally sorting a flat list, credit: https://blog.codinghorror.com/sorting-for-humans-natural-sort-order/
import re
def sort_nicely( l ):
convert = lambda text: int(text) if text.isdigit() else text
alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
l.sort( key=alphanum_key )
I just can't seem to incorporate it into my function, because I have to call lambda to select a value contained within a sublist inside a list
alphanum_keyin the code above to pull out the sublist element you want. thesort_nicelywill then operate on your specific list. so make that finalkeythe appropriate element so,key[1][3])]at the end there.