简体   繁体   English

检查列表的所有值是否都小于某个数字(如果未将其设置为该数字)

[英]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 . 对于每一个itema ,它会检查是否它是大于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.

相关问题 检查列表中的所有值是否大于某个数字 - Check if all values in list are greater than a certain number 检查列表中的所有值是否都大于特定数字x且小于y? - Check if all values in a list are bigger than certain number x and smaller than y? 列表中大于某个数字的值的数量 - number of values in a list greater than a certain number 如何检查列表中的数字是否小于列表中的另一个数字 - How to check if a number in a list is less than another number in a list 在计算大于和小于列表中某些值的值的数量时会跳过一些数字 - Some numbers are skipped in counting number of values greater and less than certain values in a list 如何从 arrays 列表中删除小于某个数字的值? - How can I remove values less than a certain number from a list of arrays? 如果它们出现的次数少于特定次数,则从 2D 字典创建值列表 - Create list of values from 2D dictionary if they show up less than a certain number of times Python校验数小于 - Python check number is less than 打印小于 python 列表中最后一个数字的所有数字 - Print all numbers less than the last number in a list in python 如果条目数少于一定数量,请以15秒为间隔删除所有条目 - Delete all the entries in 15 second intervals if the number of entries are less than a certain number
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM