【发布时间】:2018-05-22 01:27:37
【问题描述】:
我尝试将一个由多行组成的函数转换为一个仅由一行组成的函数。
多行函数如下所示:
text = “Here is a tiny example.”
def add_text_to_list(text):
new_list = []
split_text = text.splitlines() #split words in text and change type from “str” to “list”
for line in split_text:
cleared_line = line.strip() #each line of split_text is getting stripped
if cleared_line:
new_list.append(cleared_line)
return new_list
我 100% 了解此功能的工作原理和作用,但我无法将其实现为有效的“oneliner”。我也知道我需要提出一个列表理解。我要做的是(按时间顺序):
1. split words of text with text.splitlines()
2. strip lines of text.splitlines with line.strip()
3. return modified text after both of these steps
我想出的最好的:
def one_line_version(text):
return [line.strip() for line in text.splitlines()] #step 1 is missing
感谢任何形式的帮助。
编辑:感谢@Tenfrow!
【问题讨论】:
标签: python-3.x function return list-comprehension