Python - 从列表列表中过滤仅包含字母的行
给定 Matrix,编写一个Python程序来提取字符串中仅包含字母的行。
例子:
Input : test_list = [[“gfg”, “is”, “best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]]
Output : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]
Explanation : All strings with just alphabets are extracted.
Input : test_list = [[“gfg”, “is”, “!best”], [“Geeks4Geeks”, “good”], [“Gfg is good”], [“love”, “gfg”]]
Output : [[‘love’, ‘gfg’]]
Explanation : All strings with just alphabets are extracted.
方法 #1:使用isalpha() + all() +列表理解
在这里,我们使用 isalpha() 检查所有字母,并且使用 all() 来确保所有字符串只包含字母。列表理解用于遍历行。
Python3
# Python3 code to demonstrate working of
# Filter rows with only Alphabets
# Using isalpha() + all() + list comprehension
# initializing list
test_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"],
["Gfg is good"], ["love", "gfg"]]
# printing original lists
print("The original list is : " + str(test_list))
# all() checks for all strings to contain alphabets
res = [sub for sub in test_list if all(ele.isalpha() for ele in sub)]
# printing result
print("Filtered Rows : " + str(res))
Python3
# Python3 code to demonstrate working of
# Filter rows with only Alphabets
# Using filter() + lambda + join() + isalpha()
# initializing list
test_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"],
["Gfg is good"], ["love", "gfg"]]
# printing original lists
print("The original list is : " + str(test_list))
# join() used to concatenate strings
res = list(filter(lambda sub: ''.join(
[ele for ele in sub]).isalpha(), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]
Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]
方法#2:使用filter() + lambda + join() + isalpha()
在此,我们使用 join() 连接每个字符串,并使用 isalpha() 测试其是否全部为字母,如果判断返回 true,则添加。
蟒蛇3
# Python3 code to demonstrate working of
# Filter rows with only Alphabets
# Using filter() + lambda + join() + isalpha()
# initializing list
test_list = [["gfg", "is", "best"], ["Geeks4Geeks", "good"],
["Gfg is good"], ["love", "gfg"]]
# printing original lists
print("The original list is : " + str(test_list))
# join() used to concatenate strings
res = list(filter(lambda sub: ''.join(
[ele for ele in sub]).isalpha(), test_list))
# printing result
print("Filtered Rows : " + str(res))
输出:
The original list is : [[‘gfg’, ‘is’, ‘best’], [‘Geeks4Geeks’, ‘good’], [‘Gfg is good’], [‘love’, ‘gfg’]]
Filtered Rows : [[‘gfg’, ‘is’, ‘best’], [‘love’, ‘gfg’]]