2017-12-07 9 views
0

여러 줄로 구성된 함수를 한 줄로만 구성된 함수로 변환하려고합니다.함수를 "한 줄"로 변환 - 함수

다중 온라인 기능은 다음과 같습니다 :

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"이것을 구현이있다. 나는 또한 내가 목록 이해력을 생각해 내야한다는 것을 안다. 난 할 노력하고있어 (연대순으로) 이것이다 : 나는 도움이 어떤 종류의 감사

def one_line_version(text): 
    return [line.strip() for line in text.splitlines()] #step 1 is missing 

:

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 

가장 좋은 내가 함께했다.

편집 : Thanks @Tenfrow!

답변

1

당신은 정말 감사합니다 ... 내가 너무 것을 발견 지능형리스트

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

세상에 오에 대한 if를 잊어 버렸습니다 .. – Miggl

+0

내 솔루션은 있었지만 "줄 경우"그뿐만 아니라 충분했다 – Miggl