Python程序根据前缀列表打印字符串
给定一个字符串列表,这里的任务是编写一个Python程序,该程序可以提取所有字符串,其前缀与另一个列表中给定的任何自定义前缀匹配。
Input : test_list = [“geeks”, “peeks”, “meeks”, “leeks”, “mean”], pref_list = [“ge”, “ne”, “me”, “re”]
Output : [‘geeks’, ‘meeks’, ‘mean’]
Explanation : geeks, meeks and mean have prefix, ge, me and me respectively, present in prefix list.
Input : test_list = [“geeks”, “peeks”, “meeks”, “leeks”, “mean”], pref_list = [“ge”, “le”, “me”, “re”]
Output : [‘geeks’, ‘meeks’, ‘mean’, leeks]
Explanation : geeks, meeks, leeks and mean have prefix, ge, me, me and le respectively, present in prefix list.
方法 1:使用列表推导式 any() 和 startswith()
在这里,我们使用 any() 执行检查所有元素以匹配的任务,并且 startswith() 提取所有前缀。列表推导用于遍历列表中的所有字符串。
Python3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
# checking for all possible allowed prefixes using any()
res = [ele for ele in test_list if any(ele.startswith(el) for el in pref_list)]
# printing result
print("The extracted prefix strings list : " + str(res))
Python3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
# checking for all possible allowed prefixes using any()
# filtering using filter() and lambda
res = list(filter(lambda ele: any(ele.startswith(el)
for el in pref_list), test_list))
# printing result
print("The extracted prefix strings list : " + str(res))
输出:
The original list is : [‘geeks’, ‘peeks’, ‘meeks’, ‘leeks’, ‘mean’]
The extracted prefix strings list : [‘geeks’, ‘meeks’, ‘mean’]
方法 2:使用 filter()、lambda、any() 和 startswith()
这类似于上面的方法,不同之处在于过滤是使用 filter() 和 lambda 执行的。
蟒蛇3
# initializing List
test_list = ["geeks", "peeks", "meeks", "leeks", "mean"]
# printing original list
print("The original list is : " + str(test_list))
# initializing prefix list
pref_list = ["ge", "ne", "me", "re"]
# checking for all possible allowed prefixes using any()
# filtering using filter() and lambda
res = list(filter(lambda ele: any(ele.startswith(el)
for el in pref_list), test_list))
# printing result
print("The extracted prefix strings list : " + str(res))
输出:
The original list is : [‘geeks’, ‘peeks’, ‘meeks’, ‘leeks’, ‘mean’]
The extracted prefix strings list : [‘geeks’, ‘meeks’, ‘mean’]