我在fav_numbers中创建了一个数字列表。将提示用户输入2个值:开始范围和结束范围。程序将检查数字列表是否落在用户输入的范围内。如果列表中的数字在该范围内,则将打印出列表。 问题是我不确定如何检查列表中的单个数字是否在范围内。 我是python的初学者,那么最简单的方法是这样做,最好是使用循环?
n/2
答案 0 :(得分:1)
从我的角度来看,您可以按效率从高到低的方式进行选择:
如果列表已排序,仅检查边缘就足够了:
if start_range <= fav_numbers[0] and fav_numbers[-1] <= end_range:
print("numbers are in range")
显然,对列表进行排序会使您回到上一节。
或者,您可以执行以下操作:
if start_range <= min(fav_numbers) and max(fav_numbers) <= end_range:
print("numbers are in range")
最后,常规循环的优化版本将使用内置的any
/ all
函数:
if all(start_range <= num <= end_range for num in fav_numbers):
print("numbers are in range")
使用这些功能的好处是短路。这基本上意味着并非必须检查所有值。在上面的示例中(使用all
),如果数字超出范围,则环路将断开或-短路。这意味着all
的上述单行等效于更混乱的情况:
for num in fav_numbers:
if not start_range <= num <= end_range: # equivalent to if num < start_range or num > end_range
return False
return True
答案 1 :(得分:0)
您可以执行以下操作,遍历所有Enter password for [elastic]:
Reenter password for [elastic]:
Enter password for [apm_system]:
passwords must be at least [6] characters long
Try again.
Enter password for [apm_system]:
Reenter password for [apm_system]:
Passwords do not match.
Try again.
Enter password for [apm_system]:
Reenter password for [apm_system]:
Enter password for [kibana]:
Reenter password for [kibana]:
Enter password for [logstash_system]:
Reenter password for [logstash_system]:
Enter password for [beats_system]:
Reenter password for [beats_system]:
Enter password for [remote_monitoring_user]:
Reenter password for [remote_monitoring_user]:
,如果不在范围内,则将输出数字不在范围内,并返回fav_numbers
,否则,如果循环完成将返回数字
False
答案 2 :(得分:0)
一个建议是制作一个单独的函数,该函数测试所有数字是否在范围内,并返回一个True
或False
值,因为这会使它显得更整洁。 fav_numbers_are_in_range
函数内部是您要查询的循环,但是如果发现一个超出范围的数字,则它只是从该函数返回,因此不会执行整个循环。
start_range = int(input("Enter the starting number: "))
end_range = int(input("Enter the ending number: "))
# test if favourite numbers are in rage
def fav_numbers_are_in_range(fav_numbers, start_range, end_range):
for number in fav_numbers:
if number < start_range or number > end_range:
return False
return True
#find favourite numbers
def find_favourite_numbers(start_range,end_range):
fav_numbers = [70, 105, 140]
if fav_numbers_are_in_range(fav_numbers, start_range, end_range):
print("fav numbers are in range ", fav_numbers)
return fav_numbers
else:
print("not all favourite numbers are in range")
return None
find_favourite_numbers(start_range,end_range)