Python 3.x 将“多行”函数转换为“一行”函数

Python 3.x 将“多行”函数转换为“一行”函数,python-3.x,function,return,list-comprehension,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 li

我尝试将一个由多行组成的函数转换为一个只由一行组成的函数

多行函数如下所示:

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

您忘记了列表中的if

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

虽然我的解决方案是if行,这也足够了