[英]Find first element in list where value is greater than a constant
I have a list and I have a constant, and I want to know which elements in the list is greater than a constant.我有一个列表,我有一个常数,我想知道列表中的哪些元素大于常数。
ls = [2, 1, 0, 1, 3, 2, 1, 2, 1]
constant = 1.5
So I simply did:所以我只是做了:
ls >= constant
I expect it to return:我希望它会返回:
[TRUE, FALSE, FALSE, FALSE, TRUE, TRUE, FALSE, TRUE, FALSE]
But it returned an error!!!但是它返回了一个错误!!!
TypeError Traceback (most recent call last)
<ipython-input-92-91099ebca512> in <module>
----> 1 ls > constant
TypeError: '>' not supported between instances of 'list' and 'float'
How to python compare a vector to a simple constant value?如何 python 将向量与简单的常数值进行比较?
You can use a list comprehension to assess values whilst looping.您可以在循环时使用列表推导来评估值。
You need to loop when comparing elements as you cannot compare a list
to an integer
.比较元素时需要循环,因为您无法将list
与integer
进行比较。
output = [x > constant for x in ls]
#[True, False, False, False, True, True, False, True, False]
You can use map()
for this and lambda functions.您可以为此使用map()
和 lambda 函数。
print(list(map(lambda n:n>=constant, ls)))
The reason your code doesn't work is that a list and float cannot be compared.您的代码不起作用的原因是无法比较列表和浮点数。 In order for comparisons to work, they need to be of the same object (or the magic methods be pre-defined to work with custom objects).为了进行比较,它们需要具有相同的 object(或者预定义的魔术方法以使用自定义对象)。
The most Pythonic (IMO) way to get the list you describe is with a list comprehension:获取您描述的列表的最 Pythonic (IMO) 方法是使用列表理解:
>>> [n >= constant for n in ls]
[True, False, False, False, True, True, False, True, False]
It's almost the same as what you wrote, but you want to do the comparison on each individual n
value for n in ls
, rather than on ls
itself.它与您编写的内容几乎相同,但您希望对 ls 中的 n 的每个单独的n
值for n in ls
比较,而不是对ls
本身进行比较。
If you want the actual values, that's a very similar expression:如果您想要实际值,这是一个非常相似的表达式:
>>> [n for n in ls if n >= constant]
[2, 3, 2, 2]
In this case, the actual value in the list is n
, but we only include it at all if n >= constant
.在这种情况下,列表中的实际值为n
,但我们仅在if n >= constant
时才包含它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.