简体   繁体   English

在列表的列表中插入一个值

[英]Inserting a value in a list of lists

My data is as follows,我的数据如下,

data = [[2, 1, 2, 2], [2, 2, 1, 5], [1, 2, 2, 2], [2, 1, 2, 5], [2, 5, 2, 1]]

I would like to transform this such that there is a 0 at 0, 1, 2, 3 and 4th positions of the internal lists and get it look like below,我想对此进行转换,以便在内部列表的第 0、1、2、3 和第 4 个位置有一个 0,如下所示,

new_Data = [[0, 2, 1, 2, 2], [2, 0, 2, 1, 5], [1, 2, 0, 2, 2], [2, 1, 2, 0, 5], [2, 5, 2, 1, 0]]

I have tried using the following method,我尝试使用以下方法,

a = 0

for n in range(len(mRco1)-1):

  mRco1[n][n] = [a] 

But it does not seem to work.但这似乎不起作用。

Can anyone suggest how can I go about this?谁能建议我怎么能 go 关于这个?

Use the list.insert() method使用list.insert()方法

for i in range(len(data)):
    data[i].insert(i, 0)

result:结果:

print(data)
>>> [[0, 2, 1, 2, 2], [2, 0, 2, 1, 5], [1, 2, 0, 2, 2], [2, 1, 2, 0, 5], [2, 5, 2, 1, 0]]

You'd like to iterate over the lists in data , and for the n'th list, insert a 0 at position n .您想要遍历data中的列表,并且对于第 n 个列表,在 position n处插入一个0 You can use the insert function for that, and define the following loop:您可以为此使用insert function,并定义以下循环:

for i in range(len(data)):
    data[i].insert(i, 0)

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

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