简体   繁体   English

将文本文件转换为列表列表

[英]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您需要读取每一行,以逗号分隔,并将每个值解析为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]]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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