gpt4 book ai didi

python - 去除 Python 中数组列表中的空数组和零数组

转载 作者:太空宇宙 更新时间:2023-11-03 12:40:02 25 4
gpt4 key购买 nike

我正在考虑一些 Python 数据,它们是以下形式的数组列表:

LA=
[array([ 99.08322813, 253.42371683, 300.792029 ])
array([ 51.55274095, 106.29707418, 0])
array([0, 0 ,0 , 0, 0])
array([ 149.07283952, 191.45513754, 251.19610503, 393.50806493, 453.56783459])
array([ 105.61643877, 442.76668729, 450.37335607])
array([ 348.84179544])
array([], dtype=float64)]
array([0, 0 , 0])
array([ 295.05603151, 0, 451.77083268, 500.81771919])
array([ 295.05603151, 307.37232315, 451.77083268, 500.81771919])
array([ 91.86758237, 148.70156948, 488.70648486, 507.31389766])
array([ 353.68691095])
array([ 208.21919198, 246.57665959, 0, 251.33820305, 394.34266882])
array([], dtype=float64)]

在我的数据中,我得到了一些空数组:

array([], dtype=float64)] 

和用零填充的数组:

array([0, 0, 0])

我怎样才能以自动化的简单方式摆脱这两种数组

LA=
[array([ 99.08322813, 253.42371683, 300.792029 ])
array([ 51.55274095, 106.29707418, 0])
array([ 149.07283952, 191.45513754, 251.19610503, 393.50806493, 453.56783459])
array([ 105.61643877, 442.76668729, 450.37335607])
array([ 348.84179544])
array([ 295.05603151, 0, 451.77083268, 500.81771919])
array([ 295.05603151, 307.37232315, 451.77083268, 500.81771919])
array([ 91.86758237, 148.70156948, 488.70648486, 507.31389766])
array([ 353.68691095])
array([ 208.21919198, 246.57665959, 0, 251.33820305, 394.34266882])

最后我想删除零并保持数组列表格式

LA=
[array([ 99.08322813, 253.42371683, 300.792029 ])
array([ 51.55274095, 106.29707418])
array([ 149.07283952, 191.45513754, 251.19610503, 393.50806493, 453.56783459])
array([ 105.61643877, 442.76668729, 450.37335607])
array([ 348.84179544])
array([ 295.05603151, 451.77083268, 500.81771919])
array([ 295.05603151, 307.37232315, 451.77083268, 500.81771919])
array([ 91.86758237, 148.70156948, 488.70648486, 507.31389766])
array([ 353.68691095])
array([ 208.21919198, 246.57665959, 251.33820305, 394.34266882])

提前致谢

最佳答案

列表理解应该做第一部分

[x for x in LA if x.any()]

你可以用compress做第二部分

[x.compress(x) for x in LA if x.any()]

基于 Ashwini 想法的更快版本

[x.compress(x) for x in LA if count_nonzero(x)]

时间:

In [89]: %timeit [x.compress(x) for x in LA if count_nonzero(x)]  #clear winner                                
10000 loops, best of 3: 20.2 µs per loop

关于python - 去除 Python 中数组列表中的空数组和零数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20400986/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com