피곤피곤 함수라이프 ver.2
map: 시퀸스 자료형 각 원소에 동일한 function을 적용한다. 메모리효율적
map(적용가능한 함수, iterable)
Iterable(순회가능한)
Enumerate & Zip
Enumerate (열거하다) 리스트 요소를 뽑아낼때 넘버를 붙여서 내보냄
Zip(잠그다) 두개의 리스트 1대1로 합침 zip(list, list)
(본인코드 아님)
def flatten(S):
if S == []:
return S
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
return S[:1] + flatten(S[1:])
s=[[1,2],[3,4]]
print("Flattened list is: ",flatten(s))
isinstance는 데이터값과 데이터 타입을 확인 출처 : https://stackoverflow.com/questions/64745343/flatten-list-of-lists-recursively
(원문)
Ok so this is a recursive function as you have stated. It is a mostly ‘look at the next element and decide what to do with it’ method. It is started with the base case. 명시된것처럼 이것은 재귀함수입니다. 이것은 대다수 다음 원소를 보고 어떻게 시행할지 생각합니다. 이것이 기초 전제입니다.
if S == []:
return S
So this makes sense. You have an empty list, so you would expect to get back an empty list, it’s flat. -이함수에서 만약에 빈 리스트가 존재한다면 이것은 빈 리스트를 반환한다고 합니다. 평평하게
if isinstance(S[0], list):
return flatten(S[0]) + flatten(S[1:])
Next is the first ‘look at the next element, decide what to do’, if I receive a list and at the first element there is a list, I will get the program to run this same flattening method on the first element. -다음 원소를 보고 어떻게 할지 결정해봅시다. 만약에 리스트를 받고 첫번째가 리스트라면 리스트의 첫번째 원소에 대해 똑같이 평평하게 만들어 줄겁니다.
But then comes the rest of the list, we don’t know if that is flat so I will be doing the same thing for that calling flatten on that as well. -나머지 리스트에 대해 우리는 똑같이 평평하게 만들수 있을지 모릅니다.
When this returns they should both be flat lists. Adding two lists just joins them together into a new list so this would be returned up a level to the previous call of the recursive method or return to the user. -평평한 리스트를 동시에 반환한다면, 리스트는 연산이 가능하기에 두개의 리스트를 더해주어 그전의 재귀방법을 사용자에게 반환해주도록 합니다.
return S[:1] + flatten(S[1:])
From before we know that the first element of the list is not a list as the if statement was if isinstance(S[0], list) so this is just taking a list with the first element stored in it and just like before running flatten on the rest of the list as we don’t know whether the rest of the list is flat or not.
-그전에 우리는 첫번째 리스트의 원소가 리스트가 아니라면 첫번째 원소의 저장된것을 그냥 가져옴과 평탄화 작업이 시행될지 모르는 나머지를 반환합니다.
As for tracing, if you don’t have Pycharm or pdb is to complex for you. Throw in some prints within each of the if statements. Don’t be shy, you’re the one that’s going to read them. do a print(f"First element was a list: {S[0]}, {S[1:]}") that will be fine if you’re a beginner dealing with such a small amount of code. Otherwise try PDB or such.
-초보자는 PDB를 써보세요.
from functools import reduce
array2dim = [[x]*x for x in range(5)]
array = reduce(lambda x, y: x+y, array2dim)
array
LBYL( Look Before You leap) EAFP(it’s Easier Ask Forgiveness Than Permission)
try: 실행 except: 예외가 발생하면 실행 else: 예외가 발생하지 않으면 실행 finally: 무조건실행 (ex로그인시도
컴파일에러…. repl read => evaluation 사이에 에러는 예외처리가 안됨 런타임 에러 프로그램 실행중 에러 evaluation 동안 발생하는 에러
Leave a comment