列表理解窃听一个似乎不是''或'\ r \n"的字符串

Ste*_*and 1 python string list-comprehension

我读了一个包含数字列表的文件(这是我后面需要的一些标识符).

如果我的文件末尾有一个空行,我在以下代码中有一个错误:

return [ int(x)  for x in lines if not x == '' and not x == "\r\n"]
Run Code Online (Sandbox Code Playgroud)

使用以下python输出:

  [...]
File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 453, in readChange
ListNumbers
    self.changeListNumbers = loadChangeListNumbers()
  File "Z:\Projects\PyIntegrate\perforceIntegration.py", line 88, in loadChangeL
istNumbers
    return [ int(x)  for x in lines if not x == '' and not x == "\r\n"]
ValueError: invalid literal for int() with base 10: ''
Run Code Online (Sandbox Code Playgroud)

显然我的测试if not x == '' and not x == "\r\n"不足以处理这种情况.

我做错了什么?

(如果我压制文件的最后一行,即如果我让我的文件的最后一行包含一个数字,那么一切都还可以)

eum*_*iro 6

试试这个:

return [ int(line) for line in lines if line.strip() ]
Run Code Online (Sandbox Code Playgroud)

这将是strip所有空格和换行符line,如果它不是空的(即它包含一些字符,最好是数字),它会将其转换为int.

但是,ValueError如果您的文件包含除数字之外的其他字符或包含数字之间的空格,则它将失败(并且会引发).