1

I have a string of numbers that I would like to convert to a nested list. So far, I have

 with open('lifedata.txt') as f:
    table_data = [ line.split() for line in f]
print(table_data)

If the text document consists of numbers ordered like this,

0000000 0010000 0001000 0111000 0000000 0000000

The code I have so far only creates a nested list that looks like, [['0000000'], ['0010000'], ['0001000'], ['0111000'], ['0000000'], ['0000000']]

But instead, I wanted it took be [[0,0,0,0,0,0,0],[],[]] and so on. I also do not know how to convert the string into an integer. I'm just very confused on how I should manipulate the original text document to do what I want it to.

2 Answers 2

1

This is what is happening:

>>> "0000000".split()
['0000000']

Instead, call int() on every character in each string:

[[int(c) for c in line.strip()] for line in f] 

Or, via map():

[list(map(int, line.strip())) for line in f]
Sign up to request clarification or add additional context in comments.

3 Comments

If I try to call every character, it gives me invalid literal for int() with base 10: '\n'
Oh wow that worked! So was line.strip() necessary to exclude the empty space?
@George in this case, it helps to strip the newline at the end.
0

Use this ,it will return a list of containing data from each line of txt.

open('lifedata.txt').readlines()

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.