2015-04-28 29 views
0

在列表中的元組的大小爲39如何僅使用python打印輸出1次?

這裏是我的代碼:

def joinphrase(joinph,i): 
    length = len(joinph) 
    res = ['%s %s' % (joinph[i][0], joinph[i + 1][0]) 
    for i in range(length) 
     if i < length - 1 and joinph[i][2] == 'B-NP' and joinph[i + 1][2] == 'I-NP'] 
      return res 

def sentjoinphrase(joinph): 
    return [joinphrase(joinph, i) for i in range(len(joinph))] 


example = test_sents[0] 
print (sentjoinphrase(example)) 

我想加入從不同的元組兩個字符串的條件和打印輸出連接。但是根據列表中元組的大小,輸出打印了39次。

如何僅打印輸出1次?

+0

你能告訴我們你所指的元組嗎? –

回答

1

你有大量的其他問題,但對你的打印語句,它看起來像你創建與

def sentjoinphrase(joinph): 
     return [joinphrase(joinph, i) for i in range(len(joinph))] 

列表,是你最初的短語(for i in range(len(joinph))的長度,然後在你的joinphrase功能,覆蓋參數值與

for i in range(length) # Where length is equal to the length of joinph 

因爲這是一個列表理解,它只查看內部變量i,而不是傳入的參數。 這看起來好像它只是調用連接詞組短語的長度的次數,在這種情況下是39,因爲傳遞的參數是不必要的。 所以,如果你只是從joinphrase(只是多次)得到正確的值回來了,你爲什麼不刪除的說法i像這樣:

def joinphrase(phrase): 
    phrase_len = len(phrase) 
    return ['%s %s' % (phrase[i][0], joinph[i + 1][0]) 
     for i in range(phrase_len) 
     if i < phrase_len - 1 and phrase[i][2] == 'B-NP' and phrase[i + 1][2] == 'I-NP'] 

然後,你不再需要調用sentjoinphrase的說法是多餘的,你可以直接致電joinphrase

+0

謝謝..它解決了我的問題 – xera