📜  Python - 从给定的元组列表中过滤所有大写字符元组

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

Python - 从给定的元组列表中过滤所有大写字符元组

给定一个元组列表,过滤包含所有大写字符的元组。

方法#1:使用循环

在此,我们对每个元组进行迭代,并检查每个字符串是否为大写,如果不是,则从新元组中省略该元组。

Python3
# Python3 code to demonstrate working of 
# Filter uppercase characters Tuples
# Using loop
  
# initializing list
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")]
  
# printing original list
print("The original list is : " + str(test_list))
  
res_list = []
for sub in test_list:
    res = True 
    for ele in sub:
          
        # checking for uppercase
        if not ele.isupper():
            res = False 
            break
    if res:
        res_list.append(sub)
  
# printing results
print("Filtered Tuples : " + str(res_list))


Python3
# Python3 code to demonstrate working of 
# Filter uppercase characters Tuples
# Using list comprehension + all() + isupper()
  
# initializing list
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() returns true only when all strings are uppercase
res = [sub for sub in test_list if all(ele.isupper() for ele in sub)]
  
# printing results
print("Filtered Tuples : " + str(res))


输出
The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]
Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]

方法#2:使用列表理解 + all() + isupper()

在此,我们使用 all() 检查所有字符串是否为大写,列表推导提供了紧凑的问题解决方案。 isupper() 用于检查大写。

Python3

# Python3 code to demonstrate working of 
# Filter uppercase characters Tuples
# Using list comprehension + all() + isupper()
  
# initializing list
test_list = [("GFG", "IS", "BEST"), ("GFg", "AVERAGE"), ("GFG", ), ("Gfg", "CS")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() returns true only when all strings are uppercase
res = [sub for sub in test_list if all(ele.isupper() for ele in sub)]
  
# printing results
print("Filtered Tuples : " + str(res))
输出
The original list is : [('GFG', 'IS', 'BEST'), ('GFg', 'AVERAGE'), ('GFG', ), ('Gfg', 'CS')]
Filtered Tuples : [('GFG', 'IS', 'BEST'), ('GFG', )]