简体   繁体   中英

Converting a text file into a list of lists

I want to convert a text file in the format:

0,0,0,0,0,0,0,
0,1,0,0,0,0,0,
0,2,0,0,0,0,0,
0,2,0,1,0,0,0,
2,1,0,2,1,0,0,
1,1,0,1,2,1,0,

into a list of lists. However, all I can get is:

`[['0,0,0,0,0,0,0,'],
 ['0,1,0,0,0,0,0,'],
 ['0,2,0,0,0,0,0,'],
 ['0,2,0,1,0,0,0,'],
 ['2,1,0,2,1,0,0,'],
 ['1,1,0,1,2,1,0,']]`

But I don't want the quotation marks around the lists. Any help?

my code is:

while z!=0:
    y.append([f.readline().rstrip('\n')])
    z-=1  

尝试这个:

y.append([int(n) for n in f.readline().rstrip('\n').split(',')[:-1]])

在 while 循环中试试这个:

y.append([int(i) for i in f.readline().rstrip('\n').split(',') if i])

You need to read each line, split by comma, and parse each value to int

values = []
with open("data.txt") as fic:
    for line in fic:
        line = line.rstrip(",\r\n")  
        row = list(map(int, line.split(",")))
        values.append(row)

# same as 
with open("data.txt") as fic:
    values = [list(map(int, line.rstrip(",\r\n").split(","))) for line in fic]

Gives you

[[0, 0, 0, 0, 0, 0, 0], 
 [0, 1, 0, 0, 0, 0, 0], 
 [0, 2, 0, 0, 0, 0, 0], 
 [0, 2, 0, 1, 0, 0, 0], 
 [2, 1, 0, 2, 1, 0, 0], 
 [1, 1, 0, 1, 2, 1, 0]]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM