在Python中为数字矩阵创建游程长度

时间:2018-11-15 21:16:18

标签: python

我正在尝试在Python中为此矩阵创建游程长度(请参见下文),以将矩阵打印到以下格式[84, 2, 90, 2, 88, 1...]的列表中。

矩阵布局

84 84 90 90
88 93 93 93
93 93 93 93
87 87 87 94

我对游程长度循环没有太多的经验,所以任何有益的建议将不胜感激。

3 个答案:

答案 0 :(得分:1)

一种方法可能是在矩阵的每个子列表上使用列表count()方法:

>>> m = [[84, 84, 90, 90],
...      [88, 93, 93, 93],
...      [93, 93, 93, 93],
...      [87, 87, 87, 94]]

>>> l = []
>>> for row in m:
...     for x in sorted(set(row)):
...         l.extend([x, row.count(x)])

或者如果您喜欢单线:

[l.extend([x, row.count(x)]) for row in m for x in sorted(set(row))]

然后

>>> print(l)
[84, 2, 90, 2, 88, 1, 93, 3, 93, 4, 87, 3, 94, 1]

答案 1 :(得分:0)

@davedwards给出的答案非常优雅。

这是我编写的解决方案,与他在我的计算机上的解决方案具有相同的运行时间。

def run_length_encoding(matrix):
    # List for storing run length encoding
    encoding = []

    # Counts the number of occurrences
    count = 0

    # Initialize previous element to first element in matrix
    previous_element = matrix[0][0]

    for row in matrix:
        for current_element in row:
            if current_element == previous_element:
                count += 1
            else:
                encoding.append(previous_element)
                encoding.append(count)

                # Reset counter and update previous element
                count = 1
                previous_element = current_element

    # Append last element since loop exited.
    encoding.append(previous_element)
    encoding.append(count)

    return encoding

答案 2 :(得分:0)

使用高性能pyrle库进行游程算法:

# pip install pyrle
# or
# conda install -c bioconda pyrle

from pyrle import Rle
data = [int(n) for n in "84 84 90 90 88 93 93 93 93 93 93 93 87 87 87 94".split()] 
rle = Rle(data)
rle
# +--------+------+------+------+------+------+------+
# | Runs   | 2    | 2    | 1    | 7    | 3    | 1    |
# |--------+------+------+------+------+------+------|
# | Values | 84.0 | 90.0 | 88.0 | 93.0 | 87.0 | 94.0 |
# +--------+------+------+------+------+------+------+
# Rle of length 16 containing 6 elements

rle + rle
# +--------+-------+-------+-------+-------+-------+-------+
# | Runs   | 2     | 2     | 1     | 7     | 3     | 1     |
# |--------+-------+-------+-------+-------+-------+-------|
# | Values | 168.0 | 180.0 | 176.0 | 186.0 | 174.0 | 188.0 |
# +--------+-------+-------+-------+-------+-------+-------+
# Rle of length 16 containing 6 elements