从列表中移除元素并修改另一个列表在Python中

huangapple go评论66阅读模式
英文:

Removing elements from a list and modifying another list in Python

问题

import numpy as np
arJ_new = []
CB = [[[]], [np.array([9.75016872e-05]), np.array([0.00019793]), np.array([0.0001007])], [np.array([0.0002704])]]
J = [32, 1, 35]

for i in range(0, len(CB)):
    if len(CB[i]) != 0:
        J_new = J[i]
        arJ_new.append(J_new)
        J_new = list(arJ_new)
print(J_new)

当前输出是

[32, 1, 35]

期望输出是

[1, 35]
英文:

I have a list CB containing many sublists with numpy arrays. I want to identify the empty lists and generate a new list J_new by removing the specific element. I present the current and expected output.

import numpy as np
arJ_new=[]
CB = [[[]], [np.array([9.75016872e-05]), np.array([0.00019793]), np.array([0.0001007])], [np.array([0.0002704])]]
J=[32,1,35]

for i in range(0,len(CB)):
    if len(CB[i])!=0:
        J_new=J[i]
        arJ_new.append(J_new)
        J_new=list(arJ_new)
print(J_new)

The current output is

[32, 1, 35]

The expected output is

[1,35]

答案1

得分: 1

通过使用 numpy(检查大小)进行筛选:

j_new = [J[i] for i, a in enumerate(CB) if np.array(a).size != 0]

[1, 35]
英文:

By means of numpy (check size) filtering:

j_new = [J[i] for i, a in enumerate(CB) if np.array(a).size != 0]

[1, 35]

huangapple
  • 本文由 发表于 2023年2月14日 19:56:32
  • 转载请务必保留本文链接:https://go.coder-hub.com/75447490.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定