Sorting columns of data by header name

TrustyTony 0 Tallied Votes 329 Views Share

This does not look very efficient with transponation, sort and transponation back, so I am happy to hear about better alternatives.

def sort_columns(table, **kwords):
	return list(zip(*sorted(zip(*table), **kwords)))

table = [
	['c', 'b', 'd', 'aa', 'ba', 'aab'],
	list(range(2,2+6)),
	list(range(6,6+6))]

for row in sort_columns(table): 
    print(row)
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

Here is alternative with rank order of headers for reading order of the rows:

from __future__ import print_function

table = [
    ['c', 'b', 'd', 'aa', 'ba', 'aab'],
    list(range(2,2+6)),
    list(range(6,6+6))]

ranks = sorted(zip(table[0], range(len(table[0]))))
ranks= dict((r, ind) for r, (header, ind) in enumerate(ranks))
m = max(len(str(item)) for row in table  for item in row)
for row in table:
    for key in range(len(row)):
        print (' %*s' % (m, row[ranks[key]]), end=',')
    print()
TrustyTony 888 ex-Moderator Team Colleague Featured Poster

You can save the rank order in old table by slice assignment from generator:

for rowno,row in enumerate(table):
    table[rowno][:] = (row[ranks[ind]] for ind in range(len(ranks)))

print(table)
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.