Python – 提取包含所有数字字符串的元组
给定一个元组列表,只提取那些包含所有数字字符串的元组。
Input : test_list = [(“45”, “86”), (“Gfg”, “1”), (“98”, “10”)]
Output : [(’45’, ’86’), (’98’, ’10’)]
Explanation : Only number representating tuples filtered.
Input : test_list = [(“Gfg”, “1”)]
Output : []
Explanation : No tuple containing just numbers.
方法 #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')]