【问题标题】:How to threshold values in python without if statement (to zero if below threshold, same if above)如何在没有if语句的情况下在python中设置阈值(如果低于阈值则为零,如果高于阈值则相同)
【发布时间】:2018-08-09 05:18:24
【问题描述】:

我想在不使用 Python 编写“If 语句”的情况下进行内联比较。如果该值满足阈值条件,则应保持不变。如果不是,则该值应设置为 0。

在 Python 中,我似乎不允许将布尔运算符直接应用于列表。在 Matlab 中,'True' 给出 '1' 而 'False' 在数组运算中给出 0 很方便。这类似于 matlab,但在 python 中不起作用(也许与 numpy 一起使用?)。伪代码示例:

a = [1.5, 1.3, -1.4, -1.2]
a_test_positive = a>0 # Gives [1, 1, 0, 0]
positive_a_only = a.*a>0 

想要的结果:

positive_a_only>> [1.5, 1.3, 0, 0]

在 python 中最好的方法是什么?

【问题讨论】:

    标签: python arrays operators threshold


    【解决方案1】:

    你需要 -

    a = [1.5, 1.3, -1.4, -1.2]
    positive_a_only = [i if i>0 else 0 for i in a]
    
    print(positive_a_only)
    

    输出

    [1.5, 1.3, 0, 0]
    

    这被称为List Comprehension 根据您的输入和预期输出,这是执行此操作的“pythonic”方式

    列表推导式提供了一种创建列表的简洁方式。常见的 应用程序将创建新列表,其中每个元素都是 应用于另一个序列的每个成员的一些操作或 可迭代,或创建满足 a 的那些元素的子序列 一定的条件。

    你的用例就是为此而生的 :)

    【讨论】:

    • 干净!我喜欢。从 Matlab 过来,似乎应该有一种干净的方法来做到这一点,并且由于某种原因,我无法立即在堆栈溢出时找到这个答案。再次感谢
    【解决方案2】:

    如果您正在使用数值数组,可能值得查看Numpy

    import numpy as np
    
    a = np.array([1.5, 1.3, -1.4, -1.2])
    a[a < 0] = 0
    # [ 1.5  1.3  0.   0. ]
    

    【讨论】:

    • 感谢 Delgan - 这正是我在 Matlab 中习惯的做法!
    【解决方案3】:

    到目前为止,我找到的最佳答案是枚举和遍历数组,使用 python 运算符作为阈值或比较逻辑。

    关键是将索引元素乘以逻辑比较。例如

    a = 1.5
    a_positive = a * (a>0)
    print(a)
    

    按预期返回值 1.5,如果 a 为负数,则返回 0。

    下面是完整列表的示例:

    a = [1.5, 1.3 -1.4, -1.2]
    for i, element in enumerate(a):
         a[i] = element*(element>0)
    
    print(a)
    [1.5, -0.0, -0.0]
    

    希望对某人有所帮助!

    【讨论】:

      猜你喜欢
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-09-06
      • 2015-04-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多