简体   繁体   中英

How to fill up a matrix in Python using for loops

How to add zeroes to the end of a list and fill a matrix with it? Currently I have

(1,0,1,1,0)

How to fill up a matrix such that it looks like this:

[[0, 0, 0], 
 [0, 1, 0], 
 [1, 1, 0]]

In your question, you have clearly added the zeroes to the beginning of the matrix rather than the end but whatever.

To extend a list to one with 9 items with preceeding zeroes:

list_out = [0]*(9-len(list_in)) + list_in 

to extend a list to one with 9 items with trailing zeroes just reverse the order:

list_out = list_in + [0]*(9-len(list_in))

We can convert a list with 9 items to a matrix using

matrix = [li[0:3,li[3:6],li[6:9]

so eg.

list_in = [1,2,3]
li = list_in + [0]*(9-len(list_in))
matrix = [li[0:3],li[3:6],li[6:9]]

gives

[[1, 2, 3], [0, 0, 0], [0, 0, 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