简体   繁体   中英

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,

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?

Use the list.insert() method

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 . You can use the insert function for that, and define the following loop:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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