2014-10-24 4 views
0

예를 들어,이 있습니다가장 좋은 방법은 horizontly

list_of_lists = [ 
      [[1,2,3],  [4,5,6],  [7,8,9]  ], 
      [[11,22,33], [44,55,66], [77,88,99] ], 
      [[111,222,333], [444,555,666], [777,888,999]],   
     ] 

이 가장 좋은 방법 얻는 방법 :

expected_result = [ 
      [1,2,3,4,5,6,7,8,9], 
      [11,22,33,44,55,66,77,88,99], 
      [111,222,333,444,555,666,777,888,999]   
     ] 

답변

3

중첩 된 목록 내재 된 내용으로 처리하기가 너무 어렵지 않습니다.

result = [[x for inner in middle for x in inner] for middle in list_of_lists] 
0

내가 이런 식으로 할 것을

expected_result1 = list(map(lambda row: sum(row, []), list_of_lists)) 

print(expected_result) 
print(expected_result1) 

The output is: 
#[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]] 
#[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]] 
+2

사용이 매우 느려집니다 2 차 '합'때문에 더 긴 목록의 경우. – DSM

3

가장 좋은 방법은 지능형리스트로 itertools.chain.from_iterable을 사용하는 것입니다

>>> from itertools import chain 
>>> [list(chain.from_iterable(x)) for x in list_of_lists] 
[[1, 2, 3, 4, 5, 6, 7, 8, 9], [11, 22, 33, 44, 55, 66, 77, 88, 99], [111, 222, 333, 444, 555, 666, 777, 888, 999]] 

또는 NumPy와가 옵션 인 경우

In [47]: arr = np.array(list_of_lists)         

In [48]: a, b, c = arr.shape            

In [49]: arr.flatten().reshape(a, b*c)         
Out[49]: 
array([[ 1, 2, 3, 4, 5, 6, 7, 8, 9], 
     [ 11, 22, 33, 44, 55, 66, 77, 88, 99],     
     [111, 222, 333, 444, 555, 666, 777, 888, 999]]) 
1

operator.concat:

list_of_lists = [ 
      [[1,2,3],  [4,5,6],  [7,8,9]  ], 
      [[11,22,33], [44,55,66], [77,88,99] ], 
      [[111,222,333], [444,555,666], [777,888,999]],   
     ] 

import operator 
expected_result = [reduce(operator.concat, List) for List in list_of_lists)]