在Python中创建数字矩阵的运行长度

2024-09-28 01:58:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python为这个矩阵(见下文)创建一个运行长度,它将矩阵打印到以下格式的列表[84, 2, 90, 2, 88, 1...]。你知道吗

矩阵布局

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

我没有很多运行长度循环的经验,所以任何有用的建议将不胜感激。你知道吗


Tags: 列表格式矩阵经验布局建议见下文试图用
3条回答

一种方法是对矩阵中的每个子列表使用list^{}方法:

>>> 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]

@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

将高性能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

相关问题 更多 >

    热门问题