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),它就不工作了
因此,代码中包含了som
索引:
它应该是
celula = c
,因为c
已经指向了x
的每个元素中间结果
对于每个列,您将中间结果存储为:
但这只允许存储每列最后出现的
2
。也就是说,如果一行是[2,1,2,2]
,那么espf_actual = 2
,您将只存储最后一次出现的内容。您将覆盖第一个引用(在1
之前)为了避免这种情况,您需要为每一行存储中间结果。你用
espf = []*len(l)
把它做了一半,但是你以后从来没有正确地使用过它下面是一个工作示例(与初始解决方案没有太大区别):
切换行和列的关键是更改索引方法。目前,您正在沿着列表的元素进行迭代,因此,这不允许您在行和列之间切换
查看迭代的另一种方法是迭代矩阵的索引(
i, j
用于行和列),如下所示:上面的索引相当于前面的代码。它假定所有行的长度都相同(在您的示例中是这样)。将其从行更改为列很简单(提示:切换循环),我将其留给您:P
相关问题 更多 >
编程相关推荐