如何从列表中的列表中删除空格[python]

时间:2016-10-23 13:35:46

标签: python list file split integer

该文件包含:

3
7 4
2 4 6
8 5 9 3

输出:[[3],[7,4],[2,4,6],[8,5,9,3]]

我的输出:

 [[3], [7, 4], [2, 4, 6], [8, 5, 9, 3]]    
      ^       ^          ^             // don't want these spaces

我的解决方案:

def read_triangle(filename):
    f = open(filename,'r')
    triangle = []
    for line in f:
        splited = line.split()
        triangle.append([])
        for num in splited:
            triangle[-1].append(int(num))           
    f.close()
    return triangle

我需要做些什么才能删除空格?

1 个答案:

答案 0 :(得分:1)

你的输出很好。你有正确的清单。所需的输出只显示没有空格,因为输入它的人太懒了,无法点击空格键(我也时不时也会这样做)。您可以使用str(result).replace(' ', '')获得该输出,但同样没有必要。 Python解释器的列表对象的默认表示只包含可读性空间。

没有错。