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

2024-05-19 02:09:05 发布

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

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

既然这是脚本中最耗时的部分:有没有更有效的方法来实现这一点?任何有用的建议或指导都将受到高度欢迎。你知道吗


Tags: thetoinfromforlenifline
1条回答
网友
1楼 · 发布于 2024-05-19 02:09:05

您可以定义一个函数,以给定长度的步幅(在您的案例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]

相关问题 更多 >

    热门问题