📜  Python – 提取包含所有数字字符串的元组

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

Python – 提取包含所有数字字符串的元组

给定一个元组列表,只提取那些包含所有数字字符串的元组。

方法 #1:使用列表理解 + all() + isdigit()

在此,我们使用 isdigit() 检查字符串是否为数字字符串,而 all() 用于检查所有字符串。列表推导用于迭代所有元组。

Python3
# Python3 code to demonstrate working of 
# Extract Tuples with all Numeric Strings
# Using all() + list comprehension + isdigit()
  
# initializing list
test_list = [("45", "86"), ("Gfg", "1"), ("98", "10"), ("Gfg", "Best")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() checks for all digits()
res = [sub for sub in test_list if all(ele.isdigit() for ele in sub)]
  
# printing result 
print("Filtered Tuples : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Extract Tuples with all Numeric Strings
# Using lambda + filter() + isdigit()
  
# initializing list
test_list = [("45", "86"), ("Gfg", "1"), ("98", "10"), ("Gfg", "Best")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() checks for all digits()
res = list(filter(lambda sub : all(ele.isdigit() for ele in sub), test_list))
  
# printing result 
print("Filtered Tuples : " + str(res))


输出
The original list is : [('45', '86'), ('Gfg', '1'), ('98', '10'), ('Gfg', 'Best')]
Filtered Tuples : [('45', '86'), ('98', '10')]

方法 #2:使用 lambda + filter() + isdigit()

在此,我们使用 filter() + lambda 执行过滤任务,并且 isdigit() 用于检查数字。

Python3

# Python3 code to demonstrate working of 
# Extract Tuples with all Numeric Strings
# Using lambda + filter() + isdigit()
  
# initializing list
test_list = [("45", "86"), ("Gfg", "1"), ("98", "10"), ("Gfg", "Best")]
  
# printing original list
print("The original list is : " + str(test_list))
  
# all() checks for all digits()
res = list(filter(lambda sub : all(ele.isdigit() for ele in sub), test_list))
  
# printing result 
print("Filtered Tuples : " + str(res))
输出
The original list is : [('45', '86'), ('Gfg', '1'), ('98', '10'), ('Gfg', 'Best')]
Filtered Tuples : [('45', '86'), ('98', '10')]