[英]from list of integers, get number closest to and less than a given value
I am writing a code in which i have to select an integer from a list which is not only closest to a given value but also less than it at the same time. 我正在编写一个代码,其中我必须从列表中选择一个整数,该整数不仅最接近给定值,而且同时小于给定值。 How can i edit the code to meet both the conditions? 我如何编辑代码以同时满足这两个条件?
I have tried to use the in-built min() function which i have found on this site . 我试图使用在此站点上找到的内置min()函数。 It gives me that integer which is closest to a given value regardless of the integer being greater or smaller than given value. 它给我的是最接近给定值的整数,而不管该整数大于或小于给定值。
def price(my_list,real_price):
closest_number=min(my_list, key=lambda x:abs(x-real_price))
return closest_number
my_list=[101,90,70]
real_price=100
closest_number=price(my_list,real_price)
print(closest_number)
For the code above, I want the output to be 90 but I am getting 101 对于上面的代码,我希望输出为90,但得到101
Instead of min
you should get the max
of the numbers that are less than real_price
: 而不是min
,你应该得到的max
的是小于号real_price
:
def price(my_list,real_price):
return max(price for price in my_list if price <= real_price)
With this change, your code would output: 90
进行此更改后,您的代码将输出: 90
What you have is close; 你所拥有的接近; you just need to accept only numbers that are less than real_price
: 您只需要接受小于real_price
:
def price(my_list, real_price):
closest_number = min((number for number in my_list if number < real_price), key=lambda x: abs(x - real_price))
return closest_number
my_list = [101,90,70]
real_price = 100
closest_number = price(my_list, real_price)
print(closest_number)
Output: 输出:
90
Using List comprehension
and max
you can get 90. 使用List comprehension
和max
您可以获得90。
def price(my_list,real_price):
return max([x for x in my_list if ( x <= real_price )])
my_list=[101,90,70]
real_price=100
closest_number=price(my_list,real_price)
print(closest_number)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.