【问题标题】:Convert text into a list of its lines将文本转换为其行列表
【发布时间】:2012-07-26 06:20:48
【问题描述】:

我的函数输出都是在单独的行上断开的所有值,我想把它变成一个列表。

The Score
Leon the Professional
Iron Man

我想把它变成如下列表:

movies= ['The Score', 'Leon the Professional', 'Iron Man']

我该怎么做?

【问题讨论】:

  • “函数输出”是指函数返回字符串吗?或打印到标准输出?还是写入文件?
  • @Matthew 你的例子必须是有效的python,否则我们只能猜测你有什么。
  • 我们是否假设这是字符串"The Score\nLeon the Professional\nIron Man"?只需使用s.split('\n') 并阅读文档...
  • 它返回一个字符串,该字符串被分成不同的行。

标签: python list function


【解决方案1】:

假设您的输入是一个字符串。

>>> text = '''The Score
Leon the Professional
Iron Man'''
>>> text.splitlines()
['The Score', 'Leon the Professional', 'Iron Man']

有关splitlines() 函数的更多信息。

【讨论】:

  • 我真的应该更频繁地使用splitlines()。我总是默认普通的'split()
  • 出于好奇,您知道是否有理由更喜欢splitlines() 而不是split('\n')
  • @mgilson 我还要说,最好使用为特定用途制作的函数。
  • @jamylak -- 但如果他们做同样的事情,我宁愿只需要记住如何使用 1 个函数而不是 2 个函数 ;-) ...我不了解你,但我的大脑空间有限。
  • 它可能不会对小输入产生太大影响,但您可以期望 splitlines() 在用于大型数据集时更有效,因为它一直是 specifically coded 在换行符上拆分。我可能仍会使用split() 来解决点头问题,但最好记住存在特殊情况的变体。
【解决方案2】:

假设您正在从文件中读取行:

with open('lines.txt') as f:
    lines = f.readlines()
    output = []
    for line in lines:
        output.append(line.strip())

【讨论】:

  • lines = map(str.strip, f) 是一种更短、更有效的方法。列表 comp 版本为:lines = [line.strip() for line in f]
猜你喜欢
  • 2013-06-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-10
  • 2014-03-04
  • 2016-04-14
相关资源
最近更新 更多