티스토리 뷰
Stack Overflow에 자주 검색, 등록되는 문제들과 제가 개발 중 찾아 본 문제들 중에서 나중에도 찾아 볼 것 같은 문제들을 정리하고 있습니다.
Stack Overflow에서 가장 먼저 확인하게 되는 가장 높은 점수를 받은 Solution과 현 시점에 도움이 될 수 있는 가장 최근에 업데이트(최소 점수 확보)된 Solution을 각각 정리하였습니다.
아래 word cloud를 통해 이번 포스팅의 주요 키워드를 미리 확인하세요.

Flatten an irregular (arbitrarily nested) list of lists
불규칙한(임의 중첩된) 리스트 평평하게 만들기
문제 내용
Yes, I know this subject has been covered before:
네, 이 주제는 이전에 다루어졌지만,
- Python idiom to chain (flatten) an infinite iterable of finite iterables?
- Flattening a shallow list in Python
- Comprehension for flattening a sequence of sequences?
- How do I make a flat list out of a list of lists?
but as far as I know, all solutions, except for one, fail on a list like [[[1, 2, 3], [4, 5]], 6]
, where the desired output is [1, 2, 3, 4, 5, 6]
(or perhaps even better, an iterator).
[[[1, 2, 3], [4, 5]], 6]과 같은 리스트에서 원하는 출력이 [1, 2, 3, 4, 5, 6] (혹은 더 나은 방법으로 이터레이터)인 경우, 하나를 제외한 대부분의 솔루션은 실패한다는 것을 알고 있습니다.
The only solution I saw that works for an arbitrary nesting is found in this question:
임의로 중첩된 리스트에 대해 작동하는 유일한 솔루션은 다음 질문에서 찾을 수 있습니다.
def flatten(x):
result = []
for el in x:
if hasattr(el, "__iter__") and not isinstance(el, basestring):
result.extend(flatten(el))
else:
result.append(el)
return result
Is this the best approach? Did I overlook something? Any problems?
이것이 최선의 방법인가요? 놓친 부분이 있었나요? 어떤 문제가 있나요?
높은 점수를 받은 Solution
Using generator functions can make your example easier to read and improve performance.
제너레이터 함수를 사용하면 예제를 읽기 쉽게 만들고 성능을 향상시킬 수 있습니다.
Python 2
Using the Iterable
ABC added in 2.6:
2.6에 추가된 Iterable ABC를 사용하면:
from collections import Iterable
def flatten(xs):
for x in xs:
if isinstance(x, Iterable) and not isinstance(x, basestring):
for item in flatten(x):
yield item
else:
yield x
Python 3
In Python 3, basestring
is no more, but the tuple (str, bytes)
gives the same effect. Also, the yield from
operator returns an item from a generator one at a time.
파이썬 3에서는 basestring이 없지만, (str, bytes) 튜플이 동일한 효과를 줍니다. 또한, yield from 연산자는 제너레이터에서 한 번에 하나씩 항목을 반환합니다.
from collections.abc import Iterable
def flatten(xs):
for x in xs:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
가장 최근 달린 Solution
Pandas has a function that does this. It returns an iterator as you mentioned.
Pandas는 이를 수행하는 함수를 가지고 있습니다. 이는 이터레이터를 반환합니다.
In [1]: import pandas
In [2]: pandas.core.common.flatten([[[1, 2, 3], [4, 5]], 6])
Out[2]: <generator object flatten at 0x7f12ade66200>
In [3]: list(pandas.core.common.flatten([[[1, 2, 3], [4, 5]], 6]))
Out[3]: [1, 2, 3, 4, 5, 6]
출처 : https://stackoverflow.com/questions/2158395/flatten-an-irregular-arbitrarily-nested-list-of-lists
'개발 > 파이썬' 카테고리의 다른 글
딕셔너리의 모든 값들의 합을 구하는 방법 (0) | 2023.02.15 |
---|---|
판다스(Pandas) 데이터프레임(DataFrame)을 딕셔너리의 리스트로 변환하기 (0) | 2023.02.15 |
판다스 데이터프레임 열에서 값이 나타나는 빈도 계산하기 (0) | 2023.02.15 |
판다스 데이터프레임에서 열 이름을 기반으로 열 정렬하기 (0) | 2023.02.14 |
Python의 argparse.Namespace()을 dictionary로 처리하기 (0) | 2023.02.14 |