簡體   English   中英

Python:運行長度編碼?

[英]Python: Run length encoding?

我試圖理解運行長度編碼,我理解這個想法,但我不確定如何編寫它,以便 output 如下:

輸入:

data = [5, 5, 5, 10, 10]

Output:

[(5, 3), (10, 2)]

問題:通過將列表表示為對列表(2元組)來對列表進行游程長度編碼,其中每對是一個數字和該數字的“游程”的長度,如果出現數字,則長度為1一次,如果連續出現兩次,則為 2,依此類推。編寫一個 function run_length_encode(nums),它返回整數列表的游程編碼表示,nums。

有人可以向我解釋如何做到這一點並解釋每個步驟在做什么嗎? 不幸的是,我在努力掌握 Python 中的一些東西,但我正在慢慢理解它。

謝謝!

以下代碼可以解決問題,盡管它不一定是最“Pythonic”的方法:

def rle_encode(in_list):
    # Handle empty list first.

    if not in_list:
        return []

    # Init output list so that first element reflect first input item.

    out_list = [(in_list[0], 1)]

    # Then process all other items in sequence.

    for item in in_list[1:]:
        # If same as last, up count, otherwise new element with count 1.

        if item == out_list[-1][0]:
            out_list[-1] = (item, out_list[-1][1] + 1)
        else:
            out_list.append((item, 1))

    return out_list

print(rle_encode([5, 5, 5, 10, 10]))
print(rle_encode([5, 5, 5, 10, 10, 7, 7, 7, 5, 10, 7]))
print(rle_encode([]))

正如所料,output 是:

[(5, 3), (10, 2)]
[(5, 3), (10, 2), (7, 3), (5, 1), (10, 1), (7, 1)]
[]

更詳細地說,它設置了一個 output 列表,其中包含一個表示第一個輸入項的元組。 因此,對於5 ,它會創建一個列表[(5, 1)] (值為5 ,計數為1 )。

然后它處理所有其他輸入項。 如果該項目與最后一個處理的項目具有相同的值,它只是增加計數。

如果它與最后一個處理的值不同,它會在 output 列表中創建一個新的 output 值,新值和計數為 1,類似於對初始輸入值所做的操作。

因此,當您瀏覽示例中的項目時,您將看到列表如何變化:

Input     Output              Description
-----     ------              -----------
  5       [(5, 1)]            First value, init with count 1.
  5       [(5, 2)]            Same as last, increase count.
  5       [(5, 3)]            Same as last, increase count.
 10       [(5, 3), (10, 1)]   New value, append with count 1.
 10       [(5, 3), (10, 2)]   Same as last, increase count.

唯一的另一位是在開始該過程之前檢測空輸入列表,這樣您就不會嘗試使用不存在的第一個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM