[英]Check if all values of a list are less than a certain number, if not set it to that number
I have a list in python and I want to make sure that all values in the list are greater than some value. 我在python中有一个列表,我想确保列表中的所有值都大于某个值。 If not then I want to set it to that value. 如果不是,那么我想将其设置为该值。
eg: let us assume the list is 例如:让我们假设列表是
a = [1,2,3,4]
and the value to compare is 3. So I want the list to become 而要比较的值是3。所以我希望列表成为
a = [3,3,3,4]
I can do this by iterating through all the elements in the list. 我可以通过遍历列表中的所有元素来做到这一点。 Is there a better way to do that? 有更好的方法吗?
You can reconstruct the list with a simple conditional expression and list comprehension, like this 您可以使用简单的条件表达式和列表理解来重建列表,如下所示
a = [1, 2, 3, 4]
print [item if item > 3 else 3 for item in a]
# [3, 3, 3, 4]
For every item
in a
, it checks if it is greater than 3
, then use item
as it is otherwise use 3
. 对于每一个item
在a
,它会检查是否它是大于3
,然后使用item
,因为它是否则使用3
。
This is similar but very efficient than the following, 这与以下类似,但非常有效,
result = []
for item in a:
if item > 3:
result.append(item)
else:
result.append(3)
But remember that list comprehension creates a new list. 但是请记住,列表理解会创建一个新列表。 So, you have may have to do 因此,您可能必须要做
a = [item if item > 3 else 3 for item in a]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.