📜  Python – 过滤元组,元素上限为 K

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

Python – 过滤元组,元素上限为 K

给定一个元组列表,提取其中每个元素最大为 K 的元组。

方法#1:使用循环

在此,我们遍历所有元组元素,如果找到大于 K 的元素,则元组被标记并且不添加到结果列表中。

Python3
# Python3 code to demonstrate working of 
# Filter Tuple with Elements capped on K
# Using loop
  
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
res_list = []
for sub in test_list:
    res = True 
    for ele in sub:
          
        # check if any element is greater than K
        if ele > K :
            res = False 
            break
    if res:
        res_list.append(sub)
  
# printing result 
print("The filtered tuples : " + str(res_list))


Python3
# Python3 code to demonstrate working of 
# Filter Tuple with Elements capped on K
# Using all() + list comprehension
  
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# using all() to check for each tuple being in K limit
res = [sub for sub in test_list if all(ele <= K for ele in sub)]
  
# printing result 
print("The filtered tuples : " + str(res))


输出
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)]
The filtered tuples : [(4, 5, 3), (4, 3, 2)]

方法 #2:使用 all() + 列表推导

在此,我们使用 all() 检查所有元素是否处于最大 K,如果是,则将这些元组添加到结果中。

Python3

# Python3 code to demonstrate working of 
# Filter Tuple with Elements capped on K
# Using all() + list comprehension
  
# initializing list
test_list = [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K
K = 5
  
# using all() to check for each tuple being in K limit
res = [sub for sub in test_list if all(ele <= K for ele in sub)]
  
# printing result 
print("The filtered tuples : " + str(res))
输出
The original list is : [(4, 5, 3), (3, 4, 7), (4, 3, 2), (4, 7, 8)]
The filtered tuples : [(4, 5, 3), (4, 3, 2)]