I need to write a text document that has a specific number of columns (in this case there are always 16). The way I found to make this happen was: check which is the len of the array (list) where the values I want are and divide by 16, getting the number of rows enough to equate to 16 columns precisely. Surely there is a much more correct way to optimize this process.
Another question I take advantage of to ask is (because I really don’t know how to do it): how to write in 16 columns and always leave with an indentation equivalent to the largest number of that array (i.e.: 8500 = 4 characters = 4 spaces). Something like this:
Here is my code:
f = open('Questions.txt','r')
my_list = [line.split(',')[0] for line in f]
ff = open('Questions_new.txt','w')
i=0
x=len(my_list)
rows = int(round(len(my_list)//16))
for i in range(rows):
row = my_list [i::rows]
ff.write(' '.join(str(x) for x in row)+'n')
The use of line.split is because I am extracting from a text document (example below) all characters of a text document until a comma is found:
1213,4214 12312
13,1231 123
45,343
and he just keeps the information for me:
1213
13
45
If someone could help I would be thankful.
2
Answers
To answer your first question regarding the number of rows, I think your method is quite efficient. An alternative way to structure this includes:
n_rows
andn_cols
.output[n_rows][n_cols]
to right in the current rown_cols == 16
, incrementn_row++
Regarding your second question, you could:
Here are some lines of code how I would have thought of doing this:
Like with so much in python there are many different ways of achieving the same thing, so the meaning of "Surely there is a much more correct way to optimize this process" has to be specified: do you mean least amount of lines of code? most memory efficient? most readable? Depending on your definition of "correct" your code may be more correct than mine 😉
In this example the column widths are achieved through string format syntax, see e.g. python-docs. With that you could also easily adjust the alignment of your columns, etcetera.