2012-07-18 77 views
0

Python初學者在這裏。使用python解析diff結果(元組列表)

我正在與差異在這一刻。我使用google python library生成了它們。

這裏是一個什麼樣的差異的結果看起來像一個示例:

[(0, 'Ok. I just '), 
(-1, 'need to write '), 
(0, 'out a random bunch of text\nand then keep going. I'), 
(-1, ' just'), 
(0, 
    " did an enter to see how that goes and all\nthe rest of it. I know I need. Here's a skipped line.\n\nThen there is more and "), 
(-1, 't'), 
(0, 'hen there was the thing.')] 

這是一個元組列表。每個元組中的第一個元素是操作符(0 - 無變化,-1 =刪除,1 =加法)。第二個元素是從文本塊中添加或刪除的數據。

我想彙總一下這些差異結果,這樣讀者就可以通過閱讀幾行而不必閱讀可能只有30個字符或更改的文本塊來獲得更改的要點。

我朝該第一步驟是排名由字符長度的元組,然後顯示頂層3最大的變化(在它們的原始順序排列,在任一側上一個位不變文本的)。

你怎麼想我應該通過排字符長度的元組,抓住三個最長,然後重新排列它們這樣的順序是和原來一樣?

理想的情況下,結果會是這個樣子(使用上面的例子):

...只是 需要寫 了...... ......我只是 的輸入.. 。

+0

你能爲你的輸出提供的例子,你試過嗎? – sean 2012-07-18 15:42:12

+0

輸出示例在問題結束時。坦率地說,我還沒有嘗試過任何東西,因爲我不是從哪裏開始的。 – Pat 2012-07-19 00:23:13

回答

1
input = [(0, 'Ok. I just '), (-1, 'need to write '), (0, 'out a random bunch of text\nand then keep going. I'), (-1, ' just'), (0, " did an enter to see how that goes and all\nthe rest of it. I know I need. Here's a skipped line.\n\nThen there is more and "), (-1, 't'), (0, 'hen there was the thing.')] 

top_3 = [filtered_change[1] for filtered_change in sorted(sorted(enumerate(input), key=lambda change: len(change[1][1]), reverse=True)[:3])] 

或者,分步實施:

indexed_changes = enumerate(input) 
indexed_and_sorted_by_length = sorted(indexed_changes, key=lambda change: len(change[1][1]), reverse=True) 
largest_3_indexed_changes = indexed_and_sorted_by_length[:3] 
largest_3_indexed_sorted_by_index = sorted(largest_3_indexed_changes) 
largest_3_changes_in_original_order = [indexed_change[1] for indexed_change in largest_3_indexed_sorted_by_index] 
+0

這個答案完美,給了我很大的一堆東西,以瞭解當我在做其他的東西像這樣。也感謝您抽出寶貴的時間來一步步地設置它。 – Pat 2012-07-19 03:15:32