📜  Python – 如果字符串长度等于 K,则过滤字符串元组

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

Python – 如果字符串长度等于 K,则过滤字符串元组

给定元组列表,过滤元组,其元素字符串的长度等于 K。

方法#1:使用循环

在此,我们运行嵌套循环来测试每个字符串,如果等于 K,则将元组附加到结果列表中,否则将其省略。

Python3
# Python3 code to demonstrate working of 
# Filter String Tuples if String lengths equals K
# Using loop
  
# initializing list
test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoW")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
res_list = []
for sub in test_list:
    res = True 
    for ele in sub:
          
        # check using len() the lengths
        if len(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 String Tuples if String lengths equals K
# Using all() + list comprehension
  
# initializing list
test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoW")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# all checks for all lengths equals K 
res = [sub for sub in test_list if all(len(ele) == K for ele in sub)]
  
# printing result 
print("The filtered tuples : " + str(res))


输出
The original list is : [('ABC', 'Gfg', 'CS1'), ('Gfg', 'Best'), ('Gfg', 'WoW')]
The filtered tuples : [('ABC', 'Gfg', 'CS1'), ('Gfg', 'WoW')]

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

压缩方式,使用 all() 来检查长度等价和使用列表理解的迭代。

Python3

# Python3 code to demonstrate working of 
# Filter String Tuples if String lengths equals K
# Using all() + list comprehension
  
# initializing list
test_list = [("ABC", "Gfg", "CS1"), ("Gfg", "Best"), ("Gfg", "WoW")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# initializing K 
K = 3
  
# all checks for all lengths equals K 
res = [sub for sub in test_list if all(len(ele) == K for ele in sub)]
  
# printing result 
print("The filtered tuples : " + str(res))
输出
The original list is : [('ABC', 'Gfg', 'CS1'), ('Gfg', 'Best'), ('Gfg', 'WoW')]
The filtered tuples : [('ABC', 'Gfg', 'CS1'), ('Gfg', 'WoW')]