제가 생각하기엔 단순 나열) 의 목록을 만들 수 있는지 여부를 짧은보기 열거합니다 파이썬.
하지만 어쩌면 내가 할 수 있는 '는' 는 몇 가지 준활성 " one-liner" 루프,? 하지만 난 () ',' 내가 오류가 발생할 수 있는 노력은 한 것 같습니다.
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
reduce(lambda x, y: x.extend(y), l)
<! - 언어: > 랑 없음 -;
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 1, in <lambda>
AttributeError: 'NoneType' object has no attribute 'extend'
주어진 열거합니다 l ',' 목록
'flat_list = [항목으로의 하위 목록에 있는 l 항목에 대한 하위 목록에]'
즉:
flat_list = []
for sublist in l:
for item in sublist:
flat_list.append(item)
는 지금까지 shortcuts 게시하기를 빠릅니다. ('l' 은 목록 병합하려면.)
다음은 해당 기능:
flatten = lambda l: [item for sublist in l for item in sublist]
증거로 사용할 수 있습니다 ',' 티마이트 모듈에서의 표준 라이브러리.
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 143 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 969 usec per loop
$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 1.1 msec per loop
설명: '+' ('합' 묵시적 사용 등) 를 기반으로 shortcuts 높다 '는' 같은 경우 하위 목록 - L, O (L ) 는 중간 중간 결과를 가져오는 결과 목록, 각 단계에서 더 이상 새로운 목록을 얻을 수 있는 모든 항목을 객체에는 할당할지 및 이전 중간 결과를 통해 복사됨 있어야 합니다. (물론 새로 추가된 몇 가지 끝에). 따라서 실제 손실됩니다 단순성과 일반성, say you I L 각 하위 목록 항목을 않고 있다. 나는 내가 번 항목을 l 1 앞뒤로 복사됩니다 첫 번째, 두 번째 항목을 l 2 시간, 드릴링됩니다. 가 합계 총 복제본에 내가 배, 즉, "나는 x 를 x 1 에서 제외된 (l ) /2 * l '.
그냥 한 번 각 항목을 목록을 생성하는지 목록에 번역 및 복제본에 오버 (변경분이 결과 당초 거주 장소 목록) 도 정확히 한 번.
['아르투로슈자클랭 ()'] [1] 사용할 수 있습니다.
>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain(*list2d))
또는 파이썬 2.6 를 사용하여 > = ['itertools.chain.from_iterable ()'] [2] # 39, 할 수 있는 t doesn& 꺼내기 목록:
>>> import itertools
>>> list2d = [[1,2,3],[4,5,6], [7], [8,9]]
>>> merged = list(itertools.chain.from_iterable(list2d))
이 방식은 ' [항목으로의 하위 목록에 있는 l 항목에 대한 하위 목록에] 것보다 더 잘 시각이 잘 드러나' 와 너무 빠른 것으로 보인다.
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99;import itertools' 'list(itertools.chain.from_iterable(l))'
10000 loops, best of 3: 24.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' '[item for sublist in l for item in sublist]'
10000 loops, best of 3: 45.2 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'sum(l, [])'
1000 loops, best of 3: 488 usec per loop
[me@home]$ python -mtimeit -s'l=[[1,2,3],[4,5,6], [7], [8,9]]*99' 'reduce(lambda x,y: x+y,l)'
1000 loops, best of 3: 522 usec per loop
[me@home]$ python --version
Python 2.7.3
[1]: http://docs.python.org/2/library/itertools.html # 아르투로슈자클랭 [2]: http://docs.python.org/2/library/itertools.html # itertools.chain.from_iterable
>>> sum(l, [])
[1, 2, 3, 4, 5, 6, 7, 8, 9]
이 밖에 전달된 이트레이블 요소를 그냥 둔 첫 번째 인수, 두 번째 인수의 초기 값으로 of the sum (않을 경우 사용할 때 아닌 '0' 이 사건과 부여하느뇨 오류가 있습니다).
왜냐하면 당신은 합산 네스트된 열거합니다 많아진다는 것을 알 수 있습니다 ' [1.3] + [2.4]' 결과 'sum ([[1.3], [2.4]], []), 즉' 같음 ' [1.3,2.4]'.
참고로 열거합니다 때만 대한 목록. # 39 의 목록에 열거합니다 열거합니다 you&, ll, 또 다른 솔루션을 합니다.
내가 가장 테스트되었습니다 제안됩니다 솔루션과 [페르프 플로트] (https://github.com/nschloe/perfplot) (pet) 사업은 본질적으로 티마이트 내거냐 주위에서 래퍼 ','), and found "'파이썬 펑스올스트러더스 (로프라도리이콩카트, a, []) "' 가장 빠른 해결 할 수 있다. ('오페라토리어드 똑같이' 는 빠른.)
코드 플롯할 재현한다.
"'파이썬 펑스올스 임포트합니다 아르투르스 임포트합니다 누마피 임포트합니다 가져오기의 작동자 페르프 플로트 임포트합니다
데프 포퍼 (a): [항목으로의 하위 목록에 있는 품목에 대해 하위 목록에] 반품하십시오.
데프 sum_brackets (a): 반품하십시오 sum (a, [])
데프 functools_reduce (a): 펑스올스트러더스 반품하십시오 (오페라토리콘카트, a)
데프 functools_reduce_iconcat (a): 펑스올스트러더스 반품하십시오 (로프라도리이콩카트, a, [])
데프 itertools_chain (a): 반품하십시오 목록 (itertools.chain.from_iterable (a))
데프 numpy_flat (a): 반품하십시오 목록 (누마피콜라이 오프라트 (a))
데프 numpy_concatenate (a): 반품하십시오 목록 (누마피.콩카테네이트 (a))
페르프 플로t.쇼 ( 설정 람다 (λ) = n: [목록 (범위 (10))] n 커널 = [ 포퍼 sum_brackets functools_reduce functools_reduce_iconcat,, itertools_chain numpy_concatenate numpy_flat, ], n_range = [ *k ᄀ씨 대한 범위 내 (16)] 루크스 = True, 학 (접사) = true,
) "'
from functools import reduce #python 3
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(lambda x,y: x+y,l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
확장 () 는 '예' 방법 'x' 에 유용한 값을 반환하는 대신 수정되므로 (() '이' 줄일 수 있을 것으로 기대하고 있다).
더 빨리 할 수 있는 '' 버전 약간만이라도
>>> import operator
>>> l = [[1,2,3],[4,5,6], [7], [8,9]]
>>> reduce(operator.concat, l)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
이것은 외곽진입 , , 문장열 숫자임 적용되는 일반 및 컨테이너입니다 네스트된 열거합니다 혼합됨.
#from typing import Iterable
from collections import Iterable # < py38
def flatten(items):
"""Yield items from any nested iterable; see Reference."""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
for sub_x in flatten(x):
yield sub_x
else:
yield x
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(flatten(lst)) # nested lists
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
mixed = [[1, [2]], (3, 4, {5, 6}, 7), 8, "9"] # numbers, strs, nested & mixed
list(flatten(mixed))
# [1, 2, 3, 4, 5, 6, 7, 8, '9']
[dep]: https://docs.python.org/3/whatsnew/3.7.html # id3 [기초상식]: https://docs.python.org/3/library/collections.abc.html # module-collections.abc
>>> from iteration_utilities import deepflatten
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(deepflatten(l, depth=1))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> l = [[1, 2, 3], [4, [5, 6]], 7, [8, 9]]
>>> list(deepflatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
한 수준 자체가 이트레이블 플랫화할 아웃하기로 각 항목을 사용할 수도 있습니다. ['iteration_utilities.flatten'] (https://iteration-utilities.readthedocs.io/en/latest/generated/flatten.html) 를 중심으로 ['itertools.chain.from_iterable'] 그 자체가 얇은 래퍼 (https://docs.python.org/library/itertools.html # itertools.chain.from_iterable):
>>> from iteration_utilities import flatten
>>> l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
>>> list(flatten(l))
[1, 2, 3, 4, 5, 6, 7, 8, 9]
그냥 시간이 맞지 않아 일부 추가하여 따라 니코 Schl& # 246, 멜 소개된 이 질문에 대답할 didn& 함수은 포함시키십시오 # 39, t):
S # 39, it& 플롯할 로그 로그 포함하기 위해 큰 범위의 값을 스팬된. 질적 위한 곳이었다. 낮을수록 좋음.
결과에 따르면 '합' 될 경우 그 후 불과 하지만 내부 이트라블레스 이트레이블 map_layer 가장 오래 이트라블레스 itertools.chain.from_iterable iteration_utilities.deepflatten '또는' 만 ',' 번역 '합리적' 가 가장 빠른 성능을 향상시키든 네스트된 %s/dbase/ext_table. itertools.chain.from_iterable 같은 것에 의해 이미 Schl& # 246, 니코 (mer).
from itertools import chain
from functools import reduce
from collections import Iterable # or from collections.abc import Iterable
import operator
from iteration_utilities import deepflatten
def nested_list_comprehension(lsts):
return [item for sublist in lsts for item in sublist]
def itertools_chain_from_iterable(lsts):
return list(chain.from_iterable(lsts))
def pythons_sum(lsts):
return sum(lsts, [])
def reduce_add(lsts):
return reduce(lambda x, y: x + y, lsts)
def pylangs_flatten(lsts):
return list(flatten(lsts))
def flatten(items):
"""Yield items from any nested iterable; see REF."""
for x in items:
if isinstance(x, Iterable) and not isinstance(x, (str, bytes)):
yield from flatten(x)
else:
yield x
def reduce_concat(lsts):
return reduce(operator.concat, lsts)
def iteration_utilities_deepflatten(lsts):
return list(deepflatten(lsts, depth=1))
from simple_benchmark import benchmark
b = benchmark(
[nested_list_comprehension, itertools_chain_from_iterable, pythons_sum, reduce_add,
pylangs_flatten, reduce_concat, iteration_utilities_deepflatten],
arguments={2**i: [[0]*5]*(2**i) for i in range(1, 13)},
argument_name='number of inner lists'
)
b.plot()
<, sup>, 1 부인: # 39 m, 저자는 i& iqn library< /sup>;
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10000'
).timeit(100)
2.0440959930419922
이 액수는 버전 및 정보기술 (it), t # 39 분 넘게 계속 작동하고 hasn& 수행되 프로세성 아직!
중견 기업 목록:
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
20.126545906066895
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
22.242258071899414
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]] * 10'
).timeit()
16.449732065200806
작은 열거합니다 사용 및 티마이트: 번호 = 1 000 000
>>> timeit.Timer(
'[item for sublist in l for item in sublist]',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
2.4598159790039062
>>> timeit.Timer(
'reduce(lambda x,y: x+y,l)',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.5289170742034912
>>> timeit.Timer(
'sum(l, [])',
'l=[[1, 2, 3], [4, 5, 6, 7, 8], [1, 2, 3, 4, 5, 6, 7]]'
).timeit()
1.0598428249359131
함께 오페라토리아다 혼란이 있을 것 같다 ''! 두 경우 모두, 즉 '에 대한 올바른 용어를 추가했는지 열거합니다 추가할 수 없습니다.' 는 '오페라토리콘카트 concat' what you need 사용할 수 있습니다.
>>> from functools import reduce
>>> list2d = ((1, 2, 3), (4, 5, 6), (7,), (8, 9))
>>> reduce(operator.concat, list2d)
(1, 2, 3, 4, 5, 6, 7, 8, 9)
보이지 않는 절감하십시오 e0100042.log 유형, 외면하였나니 확보하십시오 튜플 다시 튜플 제공할 수 있습니다. # 39 의 시도하시겠습니까 let& 수신기마다 목록:
>>> list2d = [[1, 2, 3],[4, 5, 6], [7], [8, 9]]
>>> reduce(operator.concat, list2d)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
아하, 너회가 물러서요 바뀌엇어요.
성능 어때.
>>> list2d = [[1, 2, 3],[4, 5, 6], [7], [8, 9]]
>>> %timeit list(itertools.chain.from_iterable(list2d))
1000000 loops, best of 3: 1.36 µs per loop
'는' from_iterable 상당히 빠른! 그러나 it& # 39 을 (를) '' s no 비교, concat 줄일 수 있습니다.
>>> list2d = ((1, 2, 3),(4, 5, 6), (7,), (8, 9))
>>> %timeit reduce(operator.concat, list2d)
1000000 loops, best of 3: 492 ns per loop
>>> from django.contrib.admin.utils import flatten
>>> l = [[1,2,3], [4,5], [6]]
>>> flatten(l)
>>> [1, 2, 3, 4, 5, 6]
>>> from pandas.core.common import flatten
>>> list(flatten(l))
>>> import itertools
>>> flatten = itertools.chain.from_iterable
>>> list(flatten(l))
>>> from matplotlib.cbook import flatten
>>> list(flatten(l))
>>> from unipath.path import flatten
>>> list(flatten(l))
>>> from setuptools.namespaces import flatten
>>> list(flatten(l))
'More_itertools' 고려해보십시오 설치 패키지.
> pip install more_itertools
이 구현 출고됩니다 장치당 ['플랫화할'] [1docs] ([출처] [1code] 의 [아르투르스 비법을], [3]).
import more_itertools
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.flatten(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
현재 버전 2.4, 좀 더 복잡한 플랫화할 수 있습니다, 네스트된 이트라블레스 와 ['more_itertools.collapse'] [2docs] ([출처] [2code] 에서 이반트 했다).
lst = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
lst = [[1, 2, 3], [[4, 5, 6]], [[[7]]], 8, 9] # complex nesting
list(more_itertools.collapse(lst))
# [1, 2, 3, 4, 5, 6, 7, 8, 9]
[1code]: https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/recipes.html # 플랫화할 [2code]: https://more-itertools.readthedocs.io/en/stable/_modules/more_itertools/more.html # 축소 [1docs]: https://more-itertools.readthedocs.io/en/latest/api.html # more_itertools.flatten [2docs]: https://more-itertools.readthedocs.io/en/latest/api.html # more_itertools.collapse [3]: https://docs.python.org/3/library/itertools.html # 아르투르스 비법을
def list_flatten(l, a=None):
#check a
if a is None:
#initialize with empty list
a = []
for i in l:
if isinstance(i, list):
list_flatten(i, a)
else:
a.append(i)
return a
테스트:
In [2]: lst = [1, 2, [3], [[4]],[5,[6]]]
In [3]: lst
Out[3]: [1, 2, [3], [[4]], [5, [6]]]
In [11]: list_flatten(lst)
Out[11]: [1, 2, 3, 4, 5, 6]
재귀 버전
x = [1,2,[3,4],[5,[6,[7]]],8,9,[10]]
def flatten_list(k):
result = list()
for i in k:
if isinstance(i,list):
#The isinstance() function checks if the object (first argument) is an
#instance or subclass of classinfo class (second argument)
result.extend(flatten_list(i)) #Recursive call
else:
result.append(i)
return result
flatten_list(x)
#result = [1,2,3,4,5,6,7,8,9,10]
매플로리발스부k.플래튼 () '은' 보다 더 깊은 네스트된 열거합니다 중첩할 경우에도 사용할 예.
import matplotlib
l = [[1, 2, 3], [4, 5, 6], [7], [8, 9]]
print(list(matplotlib.cbook.flatten(l)))
l2 = [[1, 2, 3], [4, 5, 6], [7], [8, [9, 10, [11, 12, [13]]]]]
print list(matplotlib.cbook.flatten(l2))
결과:.
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]
이는 18x underscore._.flatten 보다.
Average time over 1000 trials of matplotlib.cbook.flatten: 2.55e-05 sec
Average time over 1000 trials of underscore._.flatten: 4.63e-04 sec
(time for underscore._)/(time for matplotlib.cbook) = 18.1233394636
텍스트 기반의 가변 길이 열거합니다 가져다줄래요 다룰 때 이 수락됨 오토메이티드 작동하지 않습니다. 대체 그 일을 슬라이드에서는 외곽진입 가져다줄래요.
l = ['aaa', 'bb', 'cccccc', ['xx', 'yyyyyyy']]
flat_list = [item for sublist in l for item in sublist]
print(flat_list)
['a', 'a', 'a', 'b', 'b', 'c', 'c', 'c', 'c', 'c', 'c', 'xx', 'yyyyyyy']
flat_list = []
_ = [flat_list.extend(item) if isinstance(item, list) else flat_list.append(item) for item in l if item]
print(flat_list)
['aaa', 'bb', 'cccccc', 'xx', 'yyyyyyy']