【问题标题】:Removing list in list by criteria with numpy使用 numpy 按条件删除列表中的列表
【发布时间】:2019-03-31 16:56:17
【问题描述】:

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

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])]

在这种情况下,我期望一个空列表。为什么不是所有值不同于 0 或 1 的列表(如 if 语句)都被删除?它与列表是一个numpy-array有关吗?

【问题讨论】:

    标签: python arrays list numpy


    【解决方案1】:

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

    不要删除不满足条件的数组,只需返回数组满足条件的列表:

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

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

    【讨论】:

    • 这很奇怪。这里已经有一个公认的答案。还有一个。现在只有你一个。不过也谢谢你的回答,和其他人给出的基本一样。
    猜你喜欢
    • 2019-02-19
    • 2017-01-15
    • 2022-12-23
    • 2021-11-16
    • 1970-01-01
    • 1970-01-01
    • 2018-10-13
    • 2012-12-24
    • 2011-05-17
    相关资源
    最近更新 更多