Python - 删除带有数字的行
给定一个矩阵,删除具有整数实例的行。
Input : test_list = [[4, ‘Gfg’, ‘best’], [‘gfg’, 5, ‘is’, ‘best’], [3, 5], [‘GFG’, ‘Best’]]
Output : [[‘GFG’, ‘Best’]]
Explanation : All rows with numbers are removed.
Input : test_list = [[4, ‘Gfg’, ‘best’], [‘gfg’, 5, ‘is’, ‘best’], [3, 5], [‘GFG’, ‘Best’, 1]]
Output : []
Explanation : All rows with numbers are removed. No list left.
方法 #1:使用 any() + 列表推导式
在这里,我们在任何行中使用any()检查任何整数元素,并使用列表理解来执行迭代任务。
Python3
# Python3 code to demonstrate working of
# Remove rows with Numbers
# Using list comprehension + any
# initializing lists
test_list = [[4, 'Gfg', 'best'], [
'gfg', 'is', 'best'], [3, 5], ['GFG', 'Best']]
# printing original lists
print("The original list is : " + str(test_list))
# using isinstance to check for integer and not include them
res = [sub for sub in test_list if not any(
isinstance(ele, int) for ele in sub)]
# printing result
print("The filtered rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Remove rows with Numbers
# Using filter() + lambda + any()
# initializing lists
test_list = [[4, 'Gfg', 'best'], [
'gfg', 'is', 'best'], [3, 5], ['GFG', 'Best']]
# printing original lists
print("The original list is : " + str(test_list))
# using isinstance to check for integer and not include them
# filter() used to filter with lambda fnc.
res = list(filter(lambda sub: not any(isinstance(ele, int)
for ele in sub), test_list))
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[4, ‘Gfg’, ‘best’], [‘gfg’, ‘is’, ‘best’], [3, 5], [‘GFG’, ‘Best’]]
The filtered rows : [[‘gfg’, ‘is’, ‘best’], [‘GFG’, ‘Best’]]
方法 #2:使用 filter() + lambda + any()
在此,我们使用lambda和filter()执行过滤任务, any()的使用方式与上述方法类似。
蟒蛇3
# Python3 code to demonstrate working of
# Remove rows with Numbers
# Using filter() + lambda + any()
# initializing lists
test_list = [[4, 'Gfg', 'best'], [
'gfg', 'is', 'best'], [3, 5], ['GFG', 'Best']]
# printing original lists
print("The original list is : " + str(test_list))
# using isinstance to check for integer and not include them
# filter() used to filter with lambda fnc.
res = list(filter(lambda sub: not any(isinstance(ele, int)
for ele in sub), test_list))
# printing result
print("The filtered rows : " + str(res))
输出:
The original list is : [[4, ‘Gfg’, ‘best’], [‘gfg’, ‘is’, ‘best’], [3, 5], [‘GFG’, ‘Best’]]
The filtered rows : [[‘gfg’, ‘is’, ‘best’], [‘GFG’, ‘Best’]]