📌  相关文章
📜  Python - 测试列表的元素是否在其他列表的最小/最大范围内

📅  最后修改于: 2022-05-13 01:55:18.096000             🧑  作者: Mango

Python - 测试列表的元素是否在其他列表的最小/最大范围内

给定两个列表,任务是编写一个Python程序,如果第二个列表中的所有元素都在第一个列表的最小值和最大值范围内,则返回 true。

例子:

方法 #1:使用循环 + min() + max()

在此,我们迭代第二个列表中的所有元素并比较每个元素,如果任何元素小于 min 或大于 max,则结果被标记为关闭并返回 false。

Python3
# Python3 code to demonstrate working of
# Min/Max range test from other list
# Using loop + min() + max()
  
# initializing list
test_list = [5, 6, 3, 7, 8, 10, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing range_list
range_list = [4, 7, 9, 6]
  
res = True
for ele in range_list:
  
    # flag off list in case of any off range element
    if ele  max(test_list):
        res = False
        break
  
# printing result
print("Are all elements in min/max range? : " + str(res))


Python3
# Python3 code to demonstrate working of
# Min/Max range test from other list
# Using all() + min() + max()
  
# initializing list
test_list = [5, 6, 3, 7, 8, 10, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing range_list
range_list = [4, 7, 9, 6]
  
# checking for all values in range using all()
res = all(ele >= min(test_list) and ele <= max(test_list)
          for ele in range_list)
  
# printing result
print("Are all elements in min/max range? : " + str(res))


输出
The original list is : [5, 6, 3, 7, 8, 10, 9]
Are all elements in min/max range? : True

方法 #2:使用all() + min() + max()

在此,我们使用 all() 检查范围内的所有元素,并使用 min() 和 max() 获取最大和最小元素。

蟒蛇3

# Python3 code to demonstrate working of
# Min/Max range test from other list
# Using all() + min() + max()
  
# initializing list
test_list = [5, 6, 3, 7, 8, 10, 9]
  
# printing original lists
print("The original list is : " + str(test_list))
  
# initializing range_list
range_list = [4, 7, 9, 6]
  
# checking for all values in range using all()
res = all(ele >= min(test_list) and ele <= max(test_list)
          for ele in range_list)
  
# printing result
print("Are all elements in min/max range? : " + str(res))
输出
The original list is : [5, 6, 3, 7, 8, 10, 9]
Are all elements in min/max range? : True