Python|提取 K 大小的字符串
有时,在处理大量数据时,我们可能会遇到需要提取特定大小的字符串的问题。在跨多个域的验证案例期间可能会出现此类问题。让我们讨论在Python字符串列表中处理此问题的某些方法。
方法 #1:使用列表理解 + len()
上述功能的组合可用于执行此任务。在此,我们迭代所有字符串并仅返回使用 len() 检查的 K 大小的字符串。
Python3
# Python3 code to demonstrate working of
# Extract K sized strings
# using list comprehension + len()
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize K
K = 3
# Extract K sized strings
# using list comprehension + len()
res = [ele for ele in test_list if len(ele) == K]
# printing result
print("The K sized strings are : " + str(res))
Python3
# Python3 code to demonstrate working of
# Extract K sized strings
# using filter() + lambda
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize K
K = 3
# Extract K sized strings
# using filter() + lambda
res = list(filter(lambda ele: len(ele) == K, test_list))
# printing result
print("The K sized strings are : " + str(res))
输出 :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']
方法 #2:使用 filter() + lambda
上述功能的组合可用于执行此任务。在此,我们使用 filter() 提取元素,并在 lambda函数中编译逻辑。
Python3
# Python3 code to demonstrate working of
# Extract K sized strings
# using filter() + lambda
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
# printing original list
print("The original list : " + str(test_list))
# initialize K
K = 3
# Extract K sized strings
# using filter() + lambda
res = list(filter(lambda ele: len(ele) == K, test_list))
# printing result
print("The K sized strings are : " + str(res))
输出 :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The K sized strings are : ['gfg', 'for']