[英]Need help splicing a list
I have a list of, say, size 144. I need every 16 elements to be stored in a 2-D array.我有一个大小为 144 的列表。我需要每 16 个元素存储在一个二维数组中。 In the end I would want to have a 16x9 2-D array.
最后我想要一个 16x9 的二维数组。 How do I pull these elements out in a loop and rearrange them?
如何将这些元素循环拉出并重新排列? Here is what I have so far...
这是我到目前为止...
yuH = np.zeros([N, t])
i = 0
j = 0
for i in range(t):
for j in range(len(p)):
print(p[0+j:16+j])
yuH[:,i] = p[0+j:16+j] # change to N
j = j + 16
Where N in this case is 16 and t is 9. p is my list of 144. yuH is the matrix I am trying to create.在这种情况下,N 是 16,t 是 9。p 是我的 144 列表。yuH 是我试图创建的矩阵。 alas it is not working... I get the ValueError "setting an array element with a sequence" at the line yuH[:,i] = p[0+j:16+j] after many runs.
唉,它不起作用......在多次运行后,我在 yuH[:,i] = p[0+j:16+j] 行收到 ValueError“设置具有序列的数组元素”。
Something like...就像是...
p = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20]
p = [[1, [5, 9, [13, [17,
2, 6, 10, 14, 18,
3, 7, 11, 15, 19,
4], 8] 12], 16], 20]]
If what you want is just reorganize you array p
you can just do this:如果你想要的只是重组你的数组
p
你可以这样做:
import numpy as np
N = 16
t = 9
p = np.arange(t*N) # example array p
yuH = p.reshape([t,N])
print(yuH.shape)
>>> (9, 16)
print(yuH)
>>>
[[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15]
[ 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31]
[ 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47]
[ 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63]
[ 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79]
[ 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95]
[ 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111]
[112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127]
[128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143]]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.