2013-02-02 47 views
2

如果你有一個Python長時間運行列表理解,說:如何occasionaly長期運行的Python列表理解提供反饋

from itertools import combinations 

print [w for w in (''.join(c) for c in combinations(words, 2)) if sorted(w) == letters] 

這裏的話是20萬個單詞和字母列表是字母列表;有沒有辦法打印出目前爲止已處理了多少單詞或某種其他形式的進度報告?

謝謝

回答

1

您需要將其轉換爲正常循環;不要試圖在一個副作用功能混合:

from itertools import combinations 

result = [] 
count = 0 
for w in (''.join(c) for c in combinations(words, 2)): 
    if sorted(w) == letters: 
     result.append(w) 
     count += 1 
     if count % 2000 == 0: 
      print 'Progress: {0} matching combinations found'.format(count) 

print result 

,或者,如果你想跟蹤測試組合,前if移動計數:

from itertools import combinations 

result = [] 
count = 0 
for w in (''.join(c) for c in combinations(words, 2)): 
    count += 1 
    if count % 2000 == 0: 
     print 'Progress: {0} combinations scanned'.format(count) 

    if sorted(w) == letters: 
     result.append(w) 

print result 
+0

'數+ = 0'? ';''你也不需要'count',因爲'count'在檢查前增加了,並且至少是'1'(至少它應該是)。 – Volatility

+0

@Volatility:太多的分心會導致錯誤的代碼.. :-P –

1

這裏有一臺發電機,可以將進度報告給日誌。

def log_every(seq, every): 
    for i, x in enumerate(seq): 
     if (i + 1) % every == 0: 
      logging.info('Generated %d', i) 
     yield x 

使用方法如下:

for c in log_every(combinations(words, 2), 2000): 
    ... 
相關問題