をたぶんあなたは(より効率的です)発電機の代わりに、リスト自体を使用してのような何かを行うことができます。
1つのリストでのみ実行する必要がある具体的な理由はありますか?
if any(True for tuple_list in list_of_tuple_lists if any(True for t in tuple_list if t[2]=='JJ') and any(True for t in tuple_list if t[3] == 'nsubj'))
そして、あなたの命名と一致する:
if any(True for tuple_list in parse_tree[i] if any(True for t in tuple_list if t[2]=='JJ') and any(True for t in tuple_list if t[3] == 'nsubj'))
コードは、すべてのケースのために働くことを。簡単なテスト:
import random
import time
none = [(1,2,3,4),(1,2,3,4),(1,2,3,4),(1,2,3,4)] # none of the conditions
first = [(1,2,3,4),(1,2,'JJ',4),(1,2,3,4),(1,2,3,4)]# only first of the conditions
second = [(1,2,3,4),(1,2,'test',4),(1,2,4,'nsubj'),(1,2,3,4)]# only second of the conditions
both = [(1,2,'JJ',4),(1,2,'test',4),(1,2,3,'nsubj'),(1,2,3,4)]# both of the conditions in different tuples
same = [(1,2,'JJ','nsubj'),(1,2,'test',4),(1,2,2,4),(1,2,3,4)]# both of the conditions in same tuple
possible_tuples=[none,first,second,both,same]
def our_check(list_of_tuple_lists):
if any(True for tuple_list in list_of_tuple_lists if any(True for t in tuple_list if t[2]=='JJ') and any(True for t in tuple_list if t[3] == 'nsubj')):
return True
else:
return False
def our_check_w_lists(list_of_tuple_lists):
if any([True for tuple_list in list_of_tuple_lists
if any([True for t in tuple_list if t[2]=='JJ']) and any([True for t in tuple_list if t[3] == 'nsubj'])]):
return True
else:
return False
def third_snippet(list_of_tuple_lists):
if any([tup for tup in list_of_tuple_lists if tup[2] == 'JJ']) and any([tup for tup in list_of_tuple_lists if tup[3] == 'nsubj']):
return True
else:
return False
def test(func):
test_cases = []
for n in range(100000):
test_list=[]
for i in range(10):
test_list.append(random.choice(possible_tuples))
expected = False
if both in test_list or same in test_list:
expected = True
test_case = expected, test_list
test_cases.append(test_case)
start = time.clock()
for expected, case_list in test_cases:
if expected != func(case_list):
print('%s, Fail for: %s'%(func,case_list))
return False
end = time.clock()
print('function:%s, %f'%(func, end-start))
test(our_check)
test(our_check_w_lists)
test(third_snippet)
このテスト結果は、ちょうどわずか10組の長いリストについては、発電機やリストの内包表記を使用して間の実行時間の違いを示しています。
function:<function our_check at 0x00000000028CE7B8>, 0.378369
function:<function our_check_w_lists at 0x00000000031472F0>, 1.270924
<function third_snippet at 0x00000000031E0840>, Fail for: [[...
問題は解決しませんが、ジェネレータ式を使用するとランタイムが短縮されます。あなたの最後のステートメントから '[]'を削除する - 'any'は要素が' True'になるとすぐに停止しますが、 '[]'は現在すべての要素を強制的に作成します。 – MisterMiyagi
状態とのリストの理解は悪い考えです。これを行う最も簡単な方法は、あなたが探しているそれぞれの事柄のための簡単なループとフラグです。 – jonrsharpe
@jonrsharpeそんなに気味が悪いですか? –