【问题标题】:Transform a "multiple line" - function into a "one line" - function将“多行”功能转换为“单行”功能
【发布时间】: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


    【解决方案1】:

    您在列表理解中忘记了if

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

    【讨论】:

    • 虽然我的解决方案是“if line”,但也足够了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2021-09-30
    • 1970-01-01
    相关资源
    最近更新 更多