-1

I am trying to read a text file, which has the following structure:

BUS 0   
0   1   2   3   
0   4   1   9   2   3   
BUS 1  
0   1   9   2   3   
0   1   2   3   
0   1   2   3   

It is basically a 3D list, where the nested 2D lists are matrices with an unequal number of columns and rows. The first index is denoted by the string "BUS", followed by a number. The next lines are correspond to a 2D list, with each line being a list, until the next "BUS" string. I need to assign the numbers in this text file to a 3D list in Python. The example given above should translate to :

[ [ [0,1,2,3],[0,4,1,9,2,3] ], [ [0,1,9,2,3],[0,1,2,3],[0,1,2,3] ] ]

Thanks in advance for any help.

1

2 Answers 2

0

You can try the following:

data = []

with open("file.wtv") as file_in:
    for line in file_in:
        try:
            row = [*map(int, line.strip().split())]
            data[-1].append(row)
        except ValueError:
            data.append([])

data
# [[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]], 
#  [[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]
Sign up to request clarification or add additional context in comments.

3 Comments

Instead of answering questions that demonstrate no effort on OP's part, I'd suggest a better strategy to deal with such questions is to add a comment pointing them in the right direction, and flag to close. Giving OP the code they are asking for doesn't help them because they won't learn, and it doesn't help the community because it encourages more basic questions without showing their research/coding effort.
It's you, sheriff? :D (anonymized my profile) But of course you are right. I can understand, however, that sometimes as a beginner you don't know where to start.
Thanks! This did the trick!
0

You need to write a simple parser:

test = '''BUS 0
0 1 2 3
0 4 1 9 2 3
BUS 1
0 1 9 2 3
0 1 2 3
0 1 2 3'''

out = []
for line in test.split('\n'):
    if line.startswith('BUS'):
        out.append([])
    else:
        out[-1].append(list(map(int, line.split())))

output:

[[[0, 1, 2, 3], [0, 4, 1, 9, 2, 3]],
 [[0, 1, 9, 2, 3], [0, 1, 2, 3], [0, 1, 2, 3]]]

from a file:

with open('file.txt') as f:
    out = []
    for line in f:
        if line.startswith('BUS'):
            out.append([])
        else:
            out[-1].append(list(map(int, line.split()))) 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.