Assuming I have the following nested list:
nestedlist = [[ 'ABC' , 1.5 , 2 , '8W' ],
[ 2 , 'EXT' , 5.8 , '2W' ],
[ 'DEF' , 2 , 0.2 , '2Z' ]]
for the sake of explaining my question I will refer to the inner lists as rows (i.e nestedlist[0] = row1, nestedlist[1] = row2, etc...) and collectively the items from within the inner lists that share the same ordinal index as columns (i.e. nestedlist[0][0] = item1 of column1, nestedlist[1][0] = item2 of column1, etc...)
How would I sort the rows based on the values within a particular column such that if sorted on column1 the resulting structure would look like the following:
nestedlist = [[ 2 , 'EXT' , 5.8 , '2W' ],
[ 'ABC' , 1.5 , 2 , '8W' ],
[ 'DEF' , 2 , 0.2 , '2Z' ]]
if sorted on column2 the structure would look like:
nestedlist = [[ 'ABC' , 1.5 , 2 , '8W' ],
[ 'DEF' , 2 , 0.2 , '2Z' ],
[ 2 , 'EXT' , 5.8 , '2W' ]]
if sorted on column3 the structure would look like:
nestedlist = [[ 'DEF' , 2 , 0.2 , '2Z' ],
[ 'ABC' , 1.5 , 2 , '8W' ],
[ 2 , 'EXT' , 5.8 , '2W' ]]
and lastly if sorted on column4 the structure would be:
nestedlist = [[ 2 , 'EXT' , 5.8 , '2W' ],
[ 'DEF' , 2 , 0.2 , '2Z' ],
[ 'ABC' , 1.5 , 2 , '8W' ]]
I am aware that if all of the items within a column are of the same type than the sorted(nestedlist, key=itemgetter(sortColIndex)) function can be used but I cannot for the life of me figure out how to get this to work using mixed types.
Thank you everyone for the comments and solutions you provided. searching several of the links you provided and the subsequent links there within lead me to http://productarchitect.com/code/better-natural-sort.py which addresses all of the edge cases I was encountering. Thanks again.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments