-1

I am making a program that takes a text file that looks something like this:

1
0
1
1
1

and converts it into a list:

['1','0','1','1','1']

The file has 400 lines so I want to convert it into an array that's 20 columns by 20 rows.

2
  • 3
    I am making a program can you show what you have made so far Commented Jul 5, 2019 at 8:05
  • 1
    What do you plan to do with this data once you have it in your 20 by 20 structure? Would it be worth considering numpy? Commented Jul 5, 2019 at 8:08

3 Answers 3

5

just use slicing to chunk it every 20 entries:

lines = [*range(1,401)]

rows_cols = [lines[i:i + 20] for i in range(0, len(lines), 20)]
Sign up to request clarification or add additional context in comments.

2 Comments

note: numpy.reshape does this efficiently in a single readable function call, if you're gonna do some numeric computations with it...
+1 for the one-liner solution! Can you write it as an addition/edit in a less pythonic way so it is easier to understand for python beginners?
0

Detect characters one by one counting at the same time how many characters you detected. There are two cases one when you detect the character and the counter is less than 20 and the other one when you detect the newline character for which you don't update the counter. Therefore in the first case the detected character should be assigned to the list(updating at the same time the column variable) while on the other case you just skip the newline and you continue with the next character of the text file if the counter is less than 20. In case the counter is 20 you just simply update the variable which represents the lines of the list.

Comments

0

this is save the character in 20 column, if in case no of rows are not multple of 20, it will create a list less element than 20 and add it in main list

solu =[]
leng = 20
with open('result.txt','r') as f:
    sol = f.readlines()
    tmp = []
    for i in sol:
        if len(tmp)<leng:
            tmp.append(i.strip('\n'))
        else:
            print(tmp)
            solu.append(tmp)
            tmp=[]
    solu.append(tmp)



print(solu)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.