列表中连续的特定元素的总和(python)

2024-04-24 16:03:14 发布

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

What question is asking for is, from a list of lists like the following, to return a tuple that contains tuples of all occurrences of the number 2 for a given index on the list. If there are X consecutive 2s, then it should appear only one element in the inside tuple containing X, just like this:

[[1, 2, 2, 1],
 [2, 1, 1, 2],
 [1, 1, 2, 2]]

给予

((1,), (1,), (1, 1),(2,))

[[2, 2, 2, 2],
 [2, 1, 2, 2],
 [2, 2, 1, 2]]

给予

((3,),(1, 1),(2,)(3,))

What about the same thing but not for the columns, this time, for the rows? is there a "one-line" method to do it? I mean:

[[1, 2, 2, 1],
 [2, 1, 1, 2],
 [1, 1, 2, 2]]

给予

((2,), (1, 1), (2,))

[[2, 2, 2, 2],
 [2, 1, 2, 2],
 [2, 2, 1, 2]]

给予

((4,),(1, 2),(2, 1))

我尝试过一些事情,这是其中一件事,我无法完成它,不知道以后该做什么:

l = [[2,2,2],[2,2,2],[2,2,2]]
t = (((1,1),(2,),(2,)),((2,),(2,),(1,1)))

if [x.count(0) for x in l] == [0 for x in l]:
        espf = []*len(l)
        espf2 = []
        espf_atual = 0
        contador = 0
        for x in l:
            for c in x:
                celula = x[c]
                if celula == 2:
                    espf_atual += 1
                else:
                    if celula == 1:
                        espf[contador] = [espf_atual]
                        contador += 1
                        espf_atual = 0
        espf2 += [espf_atual]
        espf_atual = 0
    print(tuple(espf2))

输出 (3,3,3)

这个输出是正确的,但是如果我改变列表(l),它就不工作了


Tags: oftheinforifiswhatlist
1条回答
网友
1楼 · 发布于 2024-04-24 16:03:14

因此,代码中包含了som

  1. 索引:

    for c in x:
        celula = x[c]
    

    它应该是celula = c,因为c已经指向了x的每个元素

  2. 中间结果

    对于每个列,您将中间结果存储为:

    espf_atual = 0
    ...
    espf_atual += 1
    ...
    espf2 += [espf_atual]
    

    但这只允许存储每列最后出现的2。也就是说,如果一行是[2,1,2,2],那么espf_actual = 2,您将只存储最后一次出现的内容。您将覆盖第一个引用(在1之前)

    为了避免这种情况,您需要为每一行存储中间结果。你用espf = []*len(l)把它做了一半,但是你以后从来没有正确地使用过它

下面是一个工作示例(与初始解决方案没有太大区别):

espf = []

for x in l:
    # Restart counters for every row
    espf_current = [] # Will store any sequences of 2
    contador = 0      # Will count consecutive 2's

    for c in x:
        celula = c
        if celula == 2:
            contador += 1    # Count number of 2
        elif celula == 1:
            if contador > 0: # Store any 2 before 1
                espf_current += [contador]
            contador = 0
    if contador > 0:         # Check if the row ends in 2
        espf_current += [contador]

    # Store results of this row in the final results
    espf += [tuple(espf_current)]
print tuple(espf)

切换行和列的关键是更改索引方法。目前,您正在沿着列表的元素进行迭代,因此,这不允许您在行和列之间切换

查看迭代的另一种方法是迭代矩阵的索引(i, j用于行和列),如下所示:

numRows = len(l)
numCols = len(l[0])

for i in range(numRows):
    for j in range(numCols):
        celula = l[i][j]

上面的索引相当于前面的代码。它假定所有行的长度都相同(在您的示例中是这样)。将其从行更改为列很简单(提示:切换循环),我将其留给您:P

相关问题 更多 >