【问题标题】:Why is stripping a newline character in Python creating a blank space as a list item?为什么在 Python 中剥离换行符会创建一个空格作为列表项?
【发布时间】:2014-03-19 22:34:11
【问题描述】:

我有以下代码:

# File declaration.

infileS = open("single.dat", 'r')
infileD = open("double.dat", 'r')
infileT = open("triple.dat", 'r')
infileHR = open("homerun.dat", 'r')
infileAB = open("atbat.dat", 'r')
infileP = open("player.dat", 'r')


# Fill up the lists.
single = infileS.read()
double = infileD.read()
triple = infileT.read()
homerun = infileHR.read()
atbat = infileAB.read()
player = infileP.read()

single = [item.rstrip() for item in single]
double = [item.rstrip() for item in double]
triple = [item.rstrip() for item in triple]
homerun = [item.rstrip() for item in homerun]
atbat = [item.rstrip() for item in atbat]
player = [item.rstrip() for item in player]

print (single)

打印什么:

['5', '', '3', '', '1', '0', '', '1', '2', '', '6', '', '9', '', '2', '0', '', '4', '', '7']

我不想要 '' 项目。我做错了什么,我能做些什么来解决这个问题?

所有 .dat 文件都是简单的记事本数字列表。 “single.dat”是一个数字列表,“enter”将它们放在不同的行上(中间没有行),看起来像:(减去,当然,包含这些数字的段落之间的空格)

5 

3 

10 

12 

6 

9 

20 

4 

7 

【问题讨论】:

  • 你能显示你正在阅读的文件吗?这对解决这个问题很有帮助。

标签: python-3.x newline


【解决方案1】:

空字符串 ('') 是如果您 strip 是所有空格(或者可能一开始就为空)所剩下的。消除这些问题的最简单方法是使用 '' 是虚假的这一事实,因此您可以通过添加 if item.strip() 在列表推导中将它们删除。

问题是您正在迭代file.read() 的输出,这是单个字符串。 Python 中的字符串是可迭代的,但这意味着当你迭代它们时,你会迭代每个字符。所以你正在做的是剥离每个单独的字符并将其添加到你的列表中——所以你所有的换行符都会变成空字符串,而不是像我想的那样被剥离。

要修复它,请使用文件对象也是可迭代的事实,并逐行迭代。这是在 Python 中逐行读取文件的惯用方式(使用 context manager 而不是单独的 open 调用):

with open('single.dat') as f:
    for line in f:
        dosomething(line)

所以,在你的列表理解中使用该模式和一些过滤,你就会万事俱备:

with open('single.dat') as f:
    single = [line.strip() for line in f if line.strip()]

【讨论】:

  • 还值得指出的是,file.read() 将所有内容都拉到一个字符串中,这就是为什么迭代它会给出'1','0' 而不是 OP 可能想要的'10'。
  • 在乐高看来,如果你把它放在with 声明中,成本会更低。
  • @LegoStormtroopr 确实如此。我只是在重写这个以首先解决最相关的问题(那个)。 :-)
【解决方案2】:

过滤掉''可能是最简单的。例如:

>>> list = ['', 'cat', 'dog', '']
>>> filter(None, list)
['cat', 'dog']

【讨论】:

    猜你喜欢
    • 2020-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 1970-01-01
    • 2014-06-18
    • 2015-02-18
    • 1970-01-01
    相关资源
    最近更新 更多