2017-10-26 4 views
2

몇 시간 동안 고생하고 있어도 해결할 수 없으므로 도와주세요! 몇 가지 튜플을 포함하는 목록의 2 목록이 있습니다.Python : 반복적으로 두 개의 튜플 목록을 요소별로 봅니다.

list_1 = [[('This', 'DT'), ('is', 'VBZ'), ('an', 'DT'), ('apple', 'NN')], [('This', 'DT'), ('Should', 'MD'), ('be', 'VB'), ('taught', 'VBN'), ('at','IN'), ('school', 'NN')], [('you', 'PRP'), ('might', 'MD'), ('take', 'VB'), ('them', 'PRP')]] 

list_2 = [[('This', 'DT'), ('is', 'VBN'), ('an', 'DT'), ('apple', 'NNS')], [('This', 'DT'), ('Should', 'VB'), ('be', 'VB'), ('taught', 'VBN'), ('at','IN'), ('school', 'NNP')], [('you', 'PRP'), ('might', 'MD'), ('take', 'VB'), ('them', 'PRP')]] 

나는 list_1list_2 요소 현명한 각 문장의 각 튜플을 비교하고, 다른 태그가에만 튜플을 반환합니다.

[(('is', 'VBZ), ('is', 'VBN)), ('apple', 'NN'), ('apple', 'NNS'))] 

왜 모든 문장을 반복하지 않습니다

def get_similarity(): 
 
     for list_1_sentence, list_2_sentence in zip(list_1, list_2): 
 
      if len(list_1) != len(list_2): 
 
       try: 
 
        raise Exception('this is an exception, some tags are missing') 
 
       except Exception as error: 
 
        print('caught this error : ', repr(error)) 
 
      else: 
 
       return [(x, y) for x, y in zip(list_1_sentence, list_2_sentence) if x != y] 
 
       
 
get_similarity()

문제

는 다른 튜플을 반환하지만 첫 번째 문장에 대한 것입니다?

답변

2

당신이 시도 할 수 있습니다 :

list_1 = [[('This', 'DT'), ('is', 'VBZ'), ('an', 'DT'), ('apple', 'NN')], [('This', 'DT'), ('Should', 'MD'), ('be', 'VB'), ('taught', 'VBN'), ('at','IN'), ('school', 'NN')], [('you', 'PRP'), ('might', 'MD'), ('take', 'VB'), ('them', 'PRP')]] 

list_2 = [[('This', 'DT'), ('is', 'VBN'), ('an', 'DT'), ('apple', 'NNS')], [('This', 'DT'), ('Should', 'VB'), ('be', 'VB'), ('taught', 'VBN'), ('at','IN'), ('school', 'NNP')], [('you', 'PRP'), ('might', 'MD'), ('take', 'VB'), ('them', 'PRP')]] 
final_tags = list(filter(lambda x:x, [[c for c, d in zip(a, b) if c[-1] != d[-1]] for a, b in zip(list_1, list_2)])) 

출력 :

[[('is', 'VBZ'), ('apple', 'NN')], [('Should', 'MD'), ('school', 'NN')]] 
+0

감사합니다. 재미있는 접근 방법은 나중에 문장과 태그 사이의 유사성 백분율을 찾고 싶습니다. 따라서 한 번만 반환하면 다른 태그가 더 편리합니다. – joasa

+0

이것은 흥미로운 접근법이지만 가능한 최소한의 판독 방법 중 하나 일 것입니다. 골프를 치는 방법, 그래서 +1 : P – HyperNeutrino

2

루프의 첫 번째 반복에서 돌아옵니다. 그러나 당신은 쉽게 항복 대신에 반환하여 발전기으로 바꿀 수 있습니다

def get_similarity(): 
    for list_1_sentence, list_2_sentence in zip(list_1, list_2): 
     #... 
     yield [(x, y) for x, y in zip(list_1_sentence, list_2_sentence) if x != y] 

list(get_similarity()) 
3

return 루프를 종료 조기

첫 번째 반복에 값을 return 때문에 루프가 한 번만 실행됩니다. 대신 다음과 같이 함수의 끝에서 모든 결과를 추적하고 반환하십시오.

def get_similarity(): 
    results = [] 
    for list_1_sentence, list_2_sentence in zip(list_1, list_2): 
     # ... 
     results.append([(x, y) for x, y in zip(list_1_sentence, list_2_sentence) if x != y]) 
    return results 

위의 내용을 확인해야합니다. Try it Online!

+0

덕분에 많이, 그것은했다! – joasa