I am trying to display a list in vertically sorted columns with number of columns decided by the user. I want to use zip()
but I can't seem to figure out how to tell it to go through n
no of lists.
#!/usr/bin/env python
import random
lst = random.sample(range(100), 30)
lst = sorted(lst)
col_size = int(raw_input('How many columns do you want?: '))
sorting = 'Vertical'
if sorting == 'Vertical':
# vertically sorted
columns = []
n = len(lst)//col_size
for i in range(0, len(lst), n):
columns.append(lst[i:i+n])
print '\nVertically Sorted:'
print columns
print zip(*columns)
This gives this result:
How many columns do you want?: 4
Vertically Sorted:
[[0, 2, 4, 11, 12, 16, 23], [24, 31, 32, 36, 41, 48, 50], [52, 54, 61, 62, 63, 64, 67], [76, 80, 81, 89, 91, 92, 94], [96, 97]]
[(0, 24, 52, 76, 96), (2, 31, 54, 80, 97)]
If I knew the number of columns (e.g. 4), I could've coded:
for c1, c2, c3, c4 in zip(columns[0], columns[1], columns[2], columns[3]):
print str(c1), str(c2).rjust(8), str(c3).rjust(8), str(c4).rjust(8)
But since I don't, how do I use zip
? As you can see I tried zip(*columns)
but that failed due to unequal no. of items in the last list.