Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
147 views
in Technique[技术] by (71.8m points)

python - Converting list into matrix

Suppose I have a list of numbers

L = [16, 5, 14, 7, 21, 9, 14, 19, 27, 1, 18, 5,27, 15, 14, 5, 27, 20, 15, 27, 15, 14, 5]

I want to convert L into 3x1 vectors until the whole L is used. We use 27 if not enough entries are there. And then we augment the vector to form a matrix.

How can I do that? Can someone please give a hint?

enter image description here

question from:https://stackoverflow.com/questions/66049911/converting-list-into-matrix

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's try to keep it simple. If your length of the list is less than a multiple of 3. Just append it with 27s!. After that you can break it into 3 rows and remaining columns. Try this method -

  1. Append the list with the number of 27s that make the list's length divisible by 3
  2. Iterate and break list over chunks of length/3 = 8 in this case.
L=[16, 5, 14, 7, 21, 9, 14, 19, 27, 1, 18, 5,27, 15, 14, 5, 27, 20, 15, 27, 15, 14, 5]

L2 = L+[27]*(3-len(L)%3) #Append list
n = int(len(L2)/3)       #Get number of cols
L3 = [L2[i:i+n] for i in range(0,len(L2),n)] #chunk list
L3
[[16, 5, 14, 7, 21, 9, 14, 19],
 [27, 1, 18, 5, 27, 15, 14, 5],
 [27, 20, 15, 27, 15, 14, 5, 27]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...