【问题标题】:How to remove spaces from lists in lists [python]如何从列表中的列表中删除空格 [python]
【发布时间】:2017-03-05 08:26:36
【问题描述】:

文件包含:

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

我必须怎么做才能删除空格?

【问题讨论】:

  • 到底是什么问题?
  • 我的输出:[[3], [7, 4], [2, 4, 6] :(每个索引之间和索引内部都有一个空格。但输出必须是没有任何空格。
  • 完全相同的列表。你确定你需要像那样把它全部打印出来吗?
  • 如何打印列表?你在用print(read_triangle(filename))
  • @HalaTwin 这与列表本身无关。它与默认的打印方式有关。

标签: python list file split integer


【解决方案1】:

你的输出很好。你有正确的清单。所需的输出只出现没有空格,因为无论谁输入它都懒得按空格键(我也时不时对此感到内疚)。您可以使用str(result).replace(' ', '') 获得该输出,但同样没有必要。 Python 解释器对列表对象的默认表示只是为了便于阅读而包含空格。

没有错。

【讨论】:

  • 我试过 str(result).replace(' ', ''),但还是不行,因为我的列表中有一个列表。
  • @HalaTwin - result = [[3],[7,4],[2,4,6],[8,5,9,3]]; str(result).replace(' ', '') 为我生成 '[[3],[7,4],[2,4,6],[8,5,9,3]]'
  • 我不断收到此错误:文件“C:\Users\user\Desktop\python\python.py”,第 11 行,在 read_triangle 返回 str(result.replace('','') ) AttributeError: 'list' 对象没有属性 'replace'
  • 好像有线OP要求,同意用户不需要,1
  • @HalaTwin - 你放错了括号。重读并重试。
猜你喜欢
  • 1970-01-01
  • 2017-11-02
  • 2018-05-03
  • 2011-06-18
  • 1970-01-01
  • 1970-01-01
  • 2020-07-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多