0

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))
FrostE1
  • 41
  • 6
  • Could you show your expected output? – SanV Apr 12 '19 at 04:57
  • 1
    have you tried `print(''.join(str_list))` – Josep Valls Apr 12 '19 at 04:58
  • put some example data in code and show your expected result - this way we could compare expected result with result created by code. – furas Apr 12 '19 at 04:58
  • maybe instead of `\t` you should use string formatting like `"{:15}\n".format(m)`. See more on [PyFormat.info](https://pyformat.info/) – furas Apr 12 '19 at 04:59
  • Use [`chunks`](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) to split your list into a rows and print each row on a newline. – awesoon Apr 12 '19 at 05:00
  • Thanks all. The answer provided by @JosepValls seems to work! although the decimals are a bit skewed and out of alignment – FrostE1 Apr 12 '19 at 05:20
  • for aligment use ie. `"{:5}".format(m)` – furas Apr 12 '19 at 05:23
  • 1
    Possible duplicate of [How do you split a list into evenly sized chunks?](https://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks) – recnac Apr 12 '19 at 05:24
  • Got what I needed from @JosepValls and furas. Any suggestions on how to mark this as complete? – FrostE1 Apr 12 '19 at 05:34

2 Answers2

0
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
Arun Augustine
  • 1,690
  • 1
  • 13
  • 20
0

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]
piet.t
  • 11,718
  • 21
  • 43
  • 52
Majo_Jose
  • 744
  • 1
  • 10
  • 24