Skip to main content
 首页 » 编程设计

python之使用 numpy 按条件删除列表中的列表

2024年11月24日13lyhabc

我有一个列表,列表如下所示:

c = [[1,0,1], [2,3,1], [0,0,0]] 

我做了一个函数 toss_non_G2(potential_list) 看起来像这样:

def  toss_non_G2(potential_list): 
    for list in potential_list: 
        if any(x not in [0,1] for x in list): 
            potential_list.remove(list) 
    return potential_list 

我试过了:

print(toss_non_G2(c)) 
>>> [[1, 0, 1], [0, 0, 0]] 

正如我所料。但是,然后我在更复杂的东西上对其进行了测试,因此问题:

import numpy as np 
from scipy.linalg import solve 
 
A = [[0.8760162 , 0.0571752 , 0.43403856], [0.04730946, 0.56278686, 0.05767958], [0.95880316, 0.9595227 , 0.02226051]] 
 
b_list = [[1, 0, 1], [1, 1, 1]] 
 
x_list = list() 
for b in b_list: 
    x = solve(A, b) 
    x_list.append(x) 
 
print(toss_non_G2(x_list)) 
>>> [array([-0.52792558,  1.49611693,  3.17236923])] 

在这种情况下,我希望得到一个空列表。为什么没有像 if 语句那样删除所有值不同于 0 或 1 的列表?它与列表是一个 numpy 数组有关吗?

请您参考如下方法:

修改您正在迭代的列表是个坏主意。

不是删除不满足条件的数组,而是简单地返回一个数组满足条件的列表:

def  toss_non_G2(potential_list): 
    return [l for l in potential_list if all(x in [0,1] for x in l)] 

如有必要,请参阅 all() 的文档.