本文介绍了如何在没有if语句的情况下在python中设置阈值(如果低于阈值则为零,如果高于阈值则为零)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想进行内联比较而不用Python编写"If语句".如果该值满足阈值条件,则应保持不变.如果不是,则应将值设置为0.

I want to do an inline comparison without writing 'If statements' in Python. If the value meets the threshold condition, it should be unchanged. If it doesn't the value should be set to 0.

在Python中,似乎不允许直接将布尔运算符应用于列表.在Matlab中,在数组运算中,"True"给出"1"而"False"给出零是很方便的.这类似于matlab,但在python中不起作用(也许使用numpy可以吗?).伪代码示例:

In Python I don't seem to be allowed to apply a boolean operator to a list directly. In Matlab, it's convenient that 'True' gives a '1' and 'False' gives a zero in array operations. This is matlab-like, but won't work in python (maybe would with numpy?). Pseudocode example:

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中执行此操作的最佳方法是什么?

What is the best way to do this in python?

推荐答案

您需要-

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]

这被称为列表理解根据您的输入和预期的输出,这是一种"Python式"的操作方式

This is known as a List ComprehensionAccording to your input and expected output, this is a "pythonic" way to do this

您的用例就是为此而创建的:)

You use case is kind of made for this :)

这篇关于如何在没有if语句的情况下在python中设置阈值(如果低于阈值则为零,如果高于阈值则为零)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-06 05:55