简体   繁体   English

如何替换给定范围内列表列表中的元素?

[英]How to replace elements in list of lists in given range?

Let's say I've defined list of lists, eg:假设我已经定义了列表列表,例如:

a = [[1,2,1,1,1],[1,1,3,4,1],[2,1,2,5,1],[1,1,2,2,3],[1,1,1,1,1]]

What I want to do is to create a loop which will be iterating through every list in list a and replace elements in given range (increasing by 1 when moving to next list) with zeros, so the output will be:我想要做的是创建一个循环,它将遍历列表a中的每个列表,并用零替换给定范围内的元素(移动到下一个列表时增加 1),因此 output 将是:

a = [[1,2,1,1,1],[0,1,3,4,1],[0,0,2,5,1],[0,0,0,2,3],[0,0,0,0,1]]

I've tried different ideas, but finally none of them seem to be working and I feel like I'm misunderstanding something.我尝试了不同的想法,但最后似乎都没有奏效,我觉得我误解了一些东西。

I've tried:我试过了:

k = 0
for i in range(len(a)):
    a[i][:k] = 0
    k += 1

But it didn't work.但它没有用。

I assume that the last element of the last sublist should be zero.我假设最后一个子列表的最后一个元素应该为零。

a = [[1,2,1,1,1],[1,1,3,4,1],[2,1,2,5,1],[1,1,2,2,3],[1,1,1,1,1]]
for i, row in enumerate(a):
    row[:i+1] = [0] * (i+1)

The 3rd line uses the Python's slice subscription, which we use to assign an iterable (list of zeros in particular) to it.第 3 行使用 Python 的 slice 订阅,我们使用它为它分配一个可迭代的(特别是零列表)。

Here's the basic way to do it:这是执行此操作的基本方法:

a = [[1,2,1,1,1],[1,1,3,4,1],[2,1,2,5,1],[1,1,2,2,3],[1,1,1,1,1]]
for i in range(len(a)):
    for j in range(i):
      a[i][j]=0
print(a)

Assuming that the first element of the first list should not be a Zero because it is "(increasing by 1 when moving to next list)"假设第一个列表的第一个元素不应该是零,因为它是“(移动到下一个列表时增加 1)”

b = []
for i, sublist in enumerate(a, 1):
   b.append([0] * i  + sublist[i:]) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM