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