Sid-Ali
Sid-Ali

Reputation: 7

How to transform a text file into a list of list

Hello everyone i am having trouble transforming this text file

____0_
33__1_
__12__
__20__
_1__11
_2____

into this list

lst = [[None, None, None, None, 0 , None],
[3 , 3 , None, None, 1 , None],
[None, None, 1 , 2 , None, None],
[None, None, 2 , 0 , None, None],
[None, 1 , None, None, 1 , 1 ],
[None, 2 , None, None, None, None]]

this is what i have done so far (I am new to python)

with open("grille1.txt") as f:
    content = f.readline()
content = [x.replace('_',"None") for x in content]
content.remove('\n')
print(content)
for j in range(len(content)):
    if content[j] == "None":
        content[j] = None
    if content[j] == "0":
        content[j] = 0
    elif content[j] == "1":
        content[j] = 1
    elif content[j] == "2":
        content[j] = 2
    elif content[j] == "3":
        content[j] = 3
print(content)

and this is my output

[None, None, None, None, 0, None]

in this case "_" takes a None and "number" needs to be replaced by his number example "0" need to be 0 on list

i hope someone can help thank you!.

Upvotes: 0

Views: 65

Answers (2)

rahlf23
rahlf23

Reputation: 9019

You can use a nested list comprehension. Note that passing a str argument to list() will convert the passed str to a list of the characters comprising that str. Then you can simply iterate over that list of characters and perform your checks (j!='_') and conversions (int(j)). The strip() function simply strips the trailing newline character '\n' from the ends of the lines:

with open("test.txt") as f:
    content = f.readlines()

lst = [[int(j) if j!='_' else None for j in list(i.strip())] for i in content]

Yields:

[
    [None, None, None, None, 0, None],
    [3, 3, None, None, 1, None],
    [None, None, 1, 2, None, None],
    [None, None, 2, 0, None, None],
    [None, 1, None, None, 1, 1],
    [None, 2, None, None, None, None]
]

Upvotes: 2

Chase
Chase

Reputation: 5615

You can do that with a one liner-

[[None if c == '_' else int(c) for c in x] for x in data.split('\n')]

Use list comprehension to iterate over the data (result of .read on the file), split by newlines, then iterate through each line itself and replace all _ with None, and the parse the other characters to integers.

Upvotes: 0

Related Questions