ex1) P243 문제1 리스트 평탄화
# P243 문제1
# 재귀함수 없이
example = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]
# example[1][0] > 4
# example[1][1] > [5, 6]
def flatten(data) :
output = []
for item in data : # [1, 2, 3], [4, [5, 6]], 7, [8, 9]
if type(item) == list : # [1, 2, 3], [4, [5, 6]], [8, 9]
for i in item : # 1, 2, 3, 4, [5, 6], 8, 9
if type(i) == list : # [5, 6]
for j in i :
output.append(j) # 5, 6
else :
output.append(i) # 1, 2, 3, 4, 8, 9
else :
output.append(item) # 7
return output
print(flatten(example))
# P243 문제1
# 재귀함수로 풀이
example = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]
def flatten(data) :
output = []
for item in data : # [1, 2, 3], [4, [5, 6]], 7, [8, 9]
if type(item) == list : # [1, 2, 3], [4, [5, 6]], [8, 9]
output += flatten(item)
else :
output.append(item) # 7
return output
print(flatten(example))