Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将文本文件转换为列表列表_Python_List - Fatal编程技术网

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

Python 将文本文件转换为列表列表,python,list,Python,List,我想将文本文件转换为以下格式: 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, 进入一个列表。然而,我能得到的只是: `[['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,'

我想将文本文件转换为以下格式:

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,
进入一个列表。然而,我能得到的只是:

`[['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,']]`
但我不想在清单上加引号。有什么帮助吗

我的代码是:

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

y.append([int(n) for n in f.readline().rstrip('\n').split(',')[:-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])

在while循环中尝试以下操作:

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

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

[[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]]

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

[[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]]

你有引号是因为它们是字符串,你需要整数没有标记你有引号是因为它们是字符串,你需要整数没有标记