如何将字符串文件导入列表列表?

时间:2013-05-23 04:05:42

标签: python list file-io python-3.3

基本上我有一个文本文件:

-1  2  0  
 0  0  0  
 0  2 -1  
-1 -2  0   
 0 -2  2   
 0  1  0   

我希望将其放入列表列表中,如下所示:

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

到目前为止,我有这段代码,但它会在列表中生成一个字符串列表。

import os  
f = open(os.path.expanduser("~/Desktop/example board.txt"))  
for line in f:  
    for i in line:  
        line = line.strip()  
        line = line.replace(' ',',')  
        line = line.replace(',,',',')  
        print(i)
        print(line)  
    b.append([line])  

产生[['-1,2,0'],['0,0,0'],['0,2,-1'],['-1,-2,0'],['0,-2,2'],['0,1,0']] 这几乎是我想要的,除了引号。

5 个答案:

答案 0 :(得分:4)

我建议只使用numpy而不是重新发明轮子......

>>> import numpy as np
>>> np.loadtxt('example board.txt', dtype=int).tolist()
[[-1, 2, 0], [0, 0, 0], [0, 2, -1], [-1, -2, 0], [0, -2, 2], [0, 1, 0]]

注意:根据您的需要,您可能会发现numpy数组比列表列表更有用。

答案 1 :(得分:2)

使用csv模块:

import csv

with open(r'example board.txt') as f:
    reader = csv.reader(f, delimiter='\t')
    lines = list(reader)

print lines

答案 2 :(得分:1)

这应该可以解决问题,因为看起来您希望数据是数字而不是字符串:

fin = open('example.txt','r')
# The list we want
list_list = []
for line in fin:
    # Split the numbers that are separated by a space. Remove the CR+LF.
    numbers = line.replace("\n","").split(" ")
    # The first list
    list1 = []
    for digit in numbers:
        list1.append(int(digit))

    # The list within the list
    list_list.append(list1)

fin.close()

这会产生如下输出:

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

答案 3 :(得分:0)

没有额外库的简单解决方案

import os

lines = []
f = open(os.path.expanduser("~/Desktop/example board.txt"))
for line in f:
    x = [int(s) for s in line.split()]
    lines.append(x)

输出:

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

答案 4 :(得分:0)

如果您使用逗号分隔值,csv模块通常是您最好的选择。如果这不合适,无论出于何种原因,那么只需使用字符串和列表内置函数就可以了解它。

你可以在列表理解中完成整个事情:

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [[int(column.strip()) for column in row.split(',')] for row in fin]

但那是不透明的,可能会被重构:

def split_fields(row):
    fields = row.split(',')
    return [int(field.strip()) for field in fields]       

with open('~/Desktop/example board.txt', 'r') as fin:
    lines = [split_fields(row) for row in fin]