如何解决将python列表切成具有特定范围内的值的子列表
我正在寻找一种将列表切成包含设置块中的值的部分的方法。例如,我要在名为z_poisson的列表中选择介于0和z_max = 32之间的值
A = 2
z_max = 32
layers = 100
poisson = np.random.poisson(A,layers)
z_poisson = np.cumsum(poisson)
print(z_poisson)
[ 3 7 8 8 8 9 9 13 14 16 18 18 21 25 30 32 33 33
36 40 42 45 47 47 48 50 54 56 58 60 60 63 63 64 66 67
70 70 71 74 81 82 84 85 87 89 93 95 98 99 99 101 103 105
108 108 108 109 110 111 113 115 116 117 118 121 121 125 126 126 127 127
128 129 135 135 137 137 139 141 141 144 147 149 151 156 158 160 163 164
164 167 171 171 173 174 176 178 178 181]
#Sample steps of length z_max
first = [x for x in z_poisson if x < z_max]
print(first)
[3,7,8,9,13,14,16,18,21,25,30,32]
因此它可以正确地用于一个块,但是我想创建另一个包含32到64之间值的列表。换句话说,我想创建向量,其值在0到z_max,z_max到2 z_max,2 z_max到3 * z_max等...。非常感谢您的帮助。谢谢
解决方法
尝试一下:
result=[[x for x in l if x < z_max*(p+1) and x>z_max*(p)] for p in range(max(l)//z_max+1)]
这将为您提供包含0-32、32-64、64-96等元素的列表列表。
[[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],[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],[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],[97,98 ,99、100 ......
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。