2017-04-11 5 views
1

내가 문자열 목록의 목록의 목록을 떠나있는 동안 목록을 평평하게하는 방법,이 같은) (장, 단락과 텍스트의 문장 표현) :(파이썬에서) 일부 중첩

[ [[ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'] ], 
    [ ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ]], 
    [[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'] ], 
    [ ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ]] ] 

I 마지막으로 다음과 같이보고, ([x for y in z for x in y]에 의해 예를 들어) completly이 목록을 평평하게하는 방법을 알고 있지만, 내가 뭘하고 싶은 부분을 평평하게하는 것입니다

[ [ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'], 
    ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ], 
    [ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'], 
    ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ] ] 

내가 루프에 대한 몇 가지로이 문제를 해결하기 위해 관리 :

semiflattend_list=list() 
for chapter in chapters: 
    senlist=list() 
    for paragraph in chapter: 
     for sentences in paragraph: 
      senlist.append(sentences) 
    semiflattend_list.append(senlist) 

하지만 더 나은 해결책이 더 있는지 궁금합니다. (내 목록의 크기가 다르기 때문에, zip 갈 수있는 방법입니다, 생각하지 않습니다.)

+1

예제는 실제로는 두 개의 다른 목록으로 된 튜플입니다. 나는 당신이 의미하는 바가 아닌 것으로 생각합니다. 당신은 괄호 나 콤마를 엉망으로 만들고 있습니다, 아마도 우리는 재현 가능한 예가 필요합니다. –

답변

1

나는 itertools.chain 방법을 사용하고 볼 수있는 가장 쉬운 변화 :

q = [ 
    [[ ['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'] ], 
     [ ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3'] ]], 
    [[ ['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'] ], 
     [ ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3'] ]] 
    ] 

r = [list(itertools.chain(*g)) for g in q] 
print(r) 

[[['chp1p1s1'], ['chp1p1s2'], ['chp1p1s3'], ['chp1p2s1'], ['chp1p2s2'], ['chp1p2s3']], 
[['chp2p1s1'], ['chp2p1s2'], ['chp2p1s3'], ['chp2p2s1'], ['chp2p2s2'], ['chp2p2s3']]] 

그래서를 어떻게 수행 [list(itertools.chain(*g)) for g in q] 평균 :

# If I only had this 
[g for g in q] 
# I would get the same I started with. 
# What I really want is to expand the nested lists 

# * before an iterable (basically) converts the iterable into its parts. 
func foo(bar, baz): 
    print(bar + " " + baz) 

lst = ["cat", "dog"] 
foo(*lst) # prints "cat dog" 

# itertools.chain accepts an arbitrary number of lists, and then outputs 
# a generator of the results: 
c = itertools.chain([1],[2]) 
# c is now <itertools.chain object at 0x10e1fce10> 
# You don't want an generator though, you want a list. Calling `list` converts that: 
o = list(c) 
# o is now [1,2] 
# Now, together: 
myList = [[2],[3]] 
flattened = list(itertools.chain(*myList)) 
# flattened is now [2,3] 
+0

이것은 실제로 그것을 해결했습니다! 어쩌면이 별표/표시 연산자를 설명해 주시겠습니까? [doc] (https://docs.python.org/3/tutorial/controlflow.html#unpacking-argument-lists)에서 이것이 어떻게 도움이되는지 설명하지 못합니다. – dia