将“多行” - 函数转换为“一行” - 函数

时间:2017-12-07 20:49:55

标签: python-3.x function return list-comprehension

我尝试将由多行组成的函数转换为仅包含一行的函数。

多行函数如下所示:

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!

1 个答案:

答案 0 :(得分:1)

您忘记了列表理解中的if

def add_text_to_list(text):
    return [line.strip() for line in text.splitlines() if line.strip()]