Is there a good way to print a large list in multiple lines? Assume that a list has 10000 elements and by writing that to a file it goes all in a single line which is difficult for text editors to open that.
I know I can iterate over the size with a counter and print \n
after each 1000 elements. For example:
my_list = [0,1,2,3,4,5,6,7,8,9]
x = 0
for i in my_list:
if x % 5 == 0:
print()
print(i, end='')
x = 1
prints
01234
56789
I wonder if there is a Python function for that to do that in a more efficient way.
CodePudding user response:
You can loop over the list in chunks and print each chunk to the file:
my_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
chunk_size = 3
with open('myfile.txt', 'w') as f:
for i in range(0, len(my_list), chunk_size):
chunk = my_list[i:i chunk_size]
print(*chunk, file=f)
This results in the file content
0 1 2
3 4 5
6 7 8
9
You can change the print()
line to format the output to your liking. To e.g. remove the spaces between the numbers, use print(*chunk, sep='', file=f)
.
CodePudding user response:
In terms of number of lines of code, hard to beat this:
chunk_size = 10
result = '\n'.join(str(my_list)[i:i chunk_size] for i in range(0, len(str(a)), chunk_size))
print(result)
Note that this does still print the commas.
Looking at your attempted solution:
my_list = [0,1,2,3,4,5,6,7,8,9]
x = 0
for i in my_list:
if x % 5 == 0:
print()
print(i, end='')
x = 1
Can be improved using enumerate
:
my_list = [0,1,2,3,4,5,6,7,8,9]
for x, i in enumerate(my_list):
if x % 5 == 0:
print()
print(i, end='')
Note that using "i" for the items here and "x" for the index is pretty gross though, since "i" is normally the index
Actually even the x%5 can be pulled into the print statement with a ternary expression:
for x, i in enumerate(my_list):
print(i, end='\n' if x%5==0 else '')