在特定条件下选择Python列表?

时间:2018-10-18 15:08:51

标签: python python-2.7 list loops row

MWE::我想执行以下操作:

M=[[0,2,1,4,9,7,6,0],
    [0,7,1,4,7,7,6,2],
    [0,5,1,4,5,5,5,0],
    [0,1,1,1,9,7,6,0],
    [0,2,1,8,8,7,8,2],
    [0,9,0,4,9,0,0,0],
    [0,2,3,4,4,6,6,0]]

s=[[1,2,3],[1,2],[4,5],[1,3,6,7]]

如果选择s [0],则操作应为

  • M的第一行不变
  • M的第二行= M的第一行+ M的第二行
  • M的第三行= M +的第三行(M的第一行+ M的第二行)
  • ,对于其余的第r行= M +的第r行(M的第1行+ M的第2行+ M的第3行+ M的第3行),r = 4、5、6、7

如果选择s [2],则操作应为

  • 第4行M不变
  • M的第5行= M的第4行+ M的第5行
  • 对于其余的第r行= M +的第r行(M的第4行+ M的第5行),r = 1,2,3,6,7

以此类推。

当s对于每个计数器随机变化时,我该如何处理。这是我尝试过的代码,但最终还是卡住了。

for r in s:
    for i in range(len(M)):
        for j in range(len(M[0])):
            if s[0][0]==1
                M[1][i]=M[1][i]

在那之后,我不知道如何去做其余的事情。我该怎么办?

2 个答案:

答案 0 :(得分:1)

以下内容将输出s的所有四个子列表的结果:

from pprint import pprint
from copy import deepcopy
M=[[0,2,1,4,9,7,6,0],
    [0,7,1,4,7,7,6,2],
    [0,5,1,4,5,5,5,0],
    [0,1,1,1,9,7,6,0],
    [0,2,1,8,8,7,8,2],
    [0,9,0,4,9,0,0,0],
    [0,2,3,4,4,6,6,0]]
s=[[1,2,3],[1,2],[4,5],[1,3,6,7]]
def f(m, s):
    new = deepcopy(m)
    for r in s:
        for row in range(r, len(m)):
            for col in range(len(m[row])):
                new[row][col] += m[r - 1][col]
    return new
for i in s:
    pprint(f(M, i), width=40)

这将输出:

[[0, 2, 1, 4, 9, 7, 6, 0],
 [0, 9, 2, 8, 16, 14, 12, 2],
 [0, 14, 3, 12, 21, 19, 17, 2],
 [0, 15, 4, 13, 30, 26, 23, 2],
 [0, 16, 4, 20, 29, 26, 25, 4],
 [0, 23, 3, 16, 30, 19, 17, 2],
 [0, 16, 6, 16, 25, 25, 23, 2]]
[[0, 2, 1, 4, 9, 7, 6, 0],
 [0, 9, 2, 8, 16, 14, 12, 2],
 [0, 14, 3, 12, 21, 19, 17, 2],
 [0, 10, 3, 9, 25, 21, 18, 2],
 [0, 11, 3, 16, 24, 21, 20, 4],
 [0, 18, 2, 12, 25, 14, 12, 2],
 [0, 11, 5, 12, 20, 20, 18, 2]]
[[0, 2, 1, 4, 9, 7, 6, 0],
 [0, 7, 1, 4, 7, 7, 6, 2],
 [0, 5, 1, 4, 5, 5, 5, 0],
 [0, 1, 1, 1, 9, 7, 6, 0],
 [0, 3, 2, 9, 17, 14, 14, 2],
 [0, 12, 2, 13, 26, 14, 14, 2],
 [0, 5, 5, 13, 21, 20, 20, 2]]
[[0, 2, 1, 4, 9, 7, 6, 0],
 [0, 9, 2, 8, 16, 14, 12, 2],
 [0, 7, 2, 8, 14, 12, 11, 0],
 [0, 8, 3, 9, 23, 19, 17, 0],
 [0, 9, 3, 16, 22, 19, 19, 2],
 [0, 16, 2, 12, 23, 12, 11, 0],
 [0, 18, 5, 16, 27, 18, 17, 0]]

答案 1 :(得分:1)

让从中选择的子列表称为lst
首先计算M[i]

i的所有lst的总和
sum_ = [0]*len(M[0])
for i in lst:
    sum_ += M[i]

现在i 不在 lst

for i in range(len(M)):
    if i in lst:
        if i == 0: continue
        for j in range(len(M[i])):
            M[i][j] += M[i-1][j]
    else:
        M[i] += sum_