Python - 提取字符串列表中以 K 开头的单词
给定短语列表,提取所有以字符K 开头的字符串。
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = l
Output : [‘learning’, ‘love’]
Explanation : All elements with L as starting letter are extracted.
Input : test_list = [“Gfg is good for learning”, “Gfg is for geeks”, “I love G4G”], K = m
Output : []
Explanation : No words started from “m” hence no word extracted.
方法 #1:使用循环 + split()
这是可以解决此问题的粗暴方式。在这里,我们将每个短语转换为单词列表,然后对于每个单词,检查它的初始字符是否为 K。
Python3
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using loop + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = []
for sub in test_list:
# splitting phrases
temp = sub.split()
for ele in temp:
# checking for matching elements
if ele[0].lower() == K.lower():
res.append(ele)
# printing result
print("The filtered elements : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using list comprehension + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()]
# printing result
print("The filtered elements : " + str(res))
输出
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']
方法 #2:使用列表理解 + split()
这是可以执行此任务的另一种方式。在此我们在单个列表理解中运行双嵌套循环并执行所需的条件检查。
Python3
# Python3 code to demonstrate working of
# Extract words starting with K in String List
# Using list comprehension + split()
# initializing list
test_list = ["Gfg is best", "Gfg is for geeks", "I love G4G"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = "g"
res = [ele for temp in test_list for ele in temp.split() if ele[0].lower() == K.lower()]
# printing result
print("The filtered elements : " + str(res))
输出
The original list is : ['Gfg is best', 'Gfg is for geeks', 'I love G4G']
The filtered elements : ['Gfg', 'Gfg', 'geeks', 'G4G']