List to row (every nth number)

Asked by At

I have a list of numbers, and I would like this list to print horizontally. Each 9 elements should print on a new row

I have the list splitting every nine elements, however I am struggling with it transposing

media_list = new_amount_list
nth_item = 9
str_list = [
    '{}\t\n'.format(m)
    if(((media_list.index(m)+1) % nth_item) == 0)
    else
    '{}\t'.format(m)
    for m in media_list
]
print('\n'.join(str_list))

2 Answers

0
Arun Augustine On
my_list = [1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,7,8,9,0]
n = 9
for lst in [my_list[i * n:(i + 1) * n] for i in range((len(my_list) + n - 1) // n )] : 
  print (*lst)

Output

1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8
9 0 1 2 3 4 5 6 7
7 8 9 0
2
Majo_Jose On

It is a simple Approach, not an expert way. import random media_list =random.sample(range(100), 99) start_index=0 increment=1

for i in media_list :
    if increment%9 ==0:
        print(media_list [start_index:increment])
        start_index=increment
    increment+=1

Output

[50, 68, 67, 5, 32, 72, 12, 96, 24]
[82, 49, 13, 81, 33, 42, 34, 90, 14]
[84, 83, 98, 61, 94, 53, 66, 80, 9]
[47, 55, 45, 73, 4, 28, 38, 71, 74]
[41, 7, 89, 22, 85, 43, 27, 16, 37]
[1, 75, 76, 78, 56, 8, 26, 44, 54]
[58, 46, 57, 31, 11, 97, 70, 64, 10]
[39, 6, 92, 0, 23, 2, 65, 48, 88]
[59, 69, 60, 19, 86, 15, 52, 99, 20]
[62, 25, 35, 91, 40, 30, 36, 3, 77]
[95, 21, 63, 51, 18, 29, 17, 93, 87]