python:如何从矩阵中有效地去除行,其中元素出现在其他行中

标签 python matrix

list = [0, 1, 2, 3, 4, 1, 5, 0, 6, 5, 7, 8, 9, 10, 11, 12, 13, 2]

列表使用“类似矩阵”

1. 0 1 2
2. 3 4 1
3. 5 0 6

...等等。我想将所有这些行写入一个新的列表/矩阵,但如果没有行,就会重复一个数字。 但是必须保留行的顺序。

到目前为止我用这个:

compa = [0,1,2,3,4,1,5,0,6,5,7,8,9,10,11,12,13,2]   #the list to be used as base
temp = [0,1,2]      #new list starts from the first element
temp2 = [12,13,2]   #new list starts from the last element
Mischzahl = 3       #defines the number of elements in a line of the "matrix"
n = 0
while n < len(compa):
    for m in range(0,len(temp)):
        if temp[m] == compa[n]:
            n = (int(n/Mischzahl) + 1) * Mischzahl - 1 #calculates the "foul" line and sets n to the next line
            break
        if (n + 1) % Mischzahl == 0 and m == len(temp) - 1 : #if the end of temp is reached, the current line is transferred to temp.
            for p in range(Mischzahl):
                temp.append(compa[Mischzahl*int(n/Mischzahl) + p])
    n += 1

反之亦然

n = len(compa) - 1
while n > 0:    #same as above but starting from last element
    for m in range(len(temp2)):
        if temp2[m] == compa[n]:
            n = (int(n/Mischzahl) - 1) * Mischzahl + Mischzahl
            break
        if (n) % Mischzahl == 0 and m == len(temp2) - 1:
            for p in range(Mischzahl):
                temp2.append(compa[Mischzahl*int(n/Mischzahl) + p])
    n = n - 1

temp 和 temp2 的结果输出:

[0, 1, 2, 3, 4, 1, 5, 0, 6, 5, 7, 8, 9, 10, 11, 12, 13, 2] #compa
[0, 1, 2, 5, 7, 8, 9, 10, 11]                              #temp
[12, 13, 2, 9, 10, 11, 5, 7, 8, 3, 4, 1]                   #temp2

由于这是脚本中最耗时的部分:是否有更有效的方法来执行此操作?非常欢迎任何有用的建议或指导。

最佳答案

您可以定义一个函数,以给定长度的步幅(在您的情况下为 3)迭代列表,检查步幅的元素是否在一组数字中,如果不是扩展列表并更新该集合.

from math import ceil

def unique_by_row(compa, stride_size=3, reverse=False):
    strides = ceil(len(compa)/stride_size)
    out = []
    check = set()
    it = range(strides)
    if reverse:
        it = reversed(it)
    for i in it:
        x = compa[stride_size*i:stride_size*(i+1)]
        if not check.intersection(x):
            out.extend(x)
            check.update(x)
    return out

测试:

compa = [0, 1, 2, 3, 4, 1, 5, 0, 6, 5, 7, 8, 9, 10, 11, 12, 13, 2]

unique_by_row(compa)
# returns:
[0, 1, 2, 5, 7, 8, 9, 10, 11]

unique_by_row(compa, reverse=True)
# returns:
[12, 13, 2, 9, 10, 11, 5, 7, 8, 3, 4, 1]

关于python:如何从矩阵中有效地去除行,其中元素出现在其他行中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48491111/

相关文章:

python - 如何表示类的实例与获取它作为输入的类之间的关系?

python - NLTK RegexpParser,通过精确匹配一个项目来分块短语

algorithm - 需要数据结构来支持矩阵运算

c# - 有windows phone 8.0平台矩阵式吗?

c - fscanf 在应该返回 1 的时候始终返回 0

python - 在 python 中从标准输入读取时管道文件描述符错误

python - 为什么在 __init__ 方法中初始化所有内容很重要?

python - Matplotlib 箱线图宽度(对数刻度)

c - 静态数组的二维数组索引失败

c++ - 在没有 GL OpenGL 矩阵函数的情况下使用矩阵移动三角形