PythonUser4
PythonUser4

Reputation: 13

Convert file content to nested list

I have a text file that consist

2, 1, 3

3, 1, 3

2, 9

My output should be

[[2,1,3],[3,1,3],[2,9]]

How do I do it?

I've tried

data=[]
for line in open(file,'r'):
    items = line.rstrip('\r\n').split('\t')
    items = [item.strip() for item in items]
    (data.append(items))
return data

But [['2,1,3'],['3,1,3'],['2,9']] came out. I don't want the output to hace the quotation.

Upvotes: 0

Views: 689

Answers (2)

etrnote
etrnote

Reputation: 136

You could also use list comprehension:

with open('file.txt', 'r') as f:
    lines = [[int(n) for n in line.strip().split(',')] for line in f.readlines() if line.strip()]

Basically, readlines() returns a list where every element is a line.

['2, 1, 3\n', '\n', '3, 1, 3\n', '\n', '2, 9'] .

We want to split each line (if it contains numbers to a list of its own

The line

[line.strip().split(',') for line in f.readlines() if line.strip()]

would give the following output:

[['2', ' 1', ' 3'], ['3', ' 1', ' 3'], ['2', ' 9']]

Since I assume the wanted output is a list of integers, we need to convert each element to int, this can also be achieved by adding using a list comprehension:

[[int(n) for n in line.strip().split(',')] for line in f.readlines() if line.strip()]

(line.strip() will check if a line is empty or not)

Output:

[[2, 1, 3], [3, 1, 3], [2, 9]]

Upvotes: 1

deadshot
deadshot

Reputation: 9061

You need to use split(',') because strip() only remove the leading and trailing whitespaces.

After splitting you can convert to string to integer using map(int, line.strip().split(',')). This will call int() function on every element in the list.

res = [list(map(int, line.strip().split(','))) for line in open('test.txt')]

Output:

[[2, 1, 3], [3, 1, 3], [2, 9]]

Upvotes: 0

Related Questions