📜  Python – 提取范围大小的字符串

📅  最后修改于: 2022-05-13 01:55:30.707000             🧑  作者: Mango

Python – 提取范围大小的字符串

有时,在处理大量数据时,我们可能会遇到需要提取特定范围大小的字符串的问题。在跨多个域的验证案例期间可能会出现此类问题。让我们讨论在Python字符串列表中处理此问题的某些方法。
方法 #1:使用列表理解 + len()
上述功能的组合可用于执行此任务。在此,我们迭代所有字符串并仅返回使用 len() 检查的范围大小的字符串。

Python3
# Python3 code to demonstrate working of
# Range length Strings extraction
# using list comprehension + len()
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize i, j
i, j = 2, 3
 
# Range length Strings extraction
# using list comprehension + len()
res = [ele for ele in test_list if len(ele) >= i and len(ele) <= j]
 
# printing result
print("The range sized strings are : " + str(res))


Python3
# Python3 code to demonstrate working of
# Range length Strings extraction
# using filter() + lambda
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize i, j
i, j = 2, 3
 
# Range length Strings extraction
# using filter() + lambda
res = list(filter(lambda ele: len(ele) >= i and len(ele) <= j, test_list))
 
# printing result
print("The range sized strings are : " + str(res))


输出 :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The range sized strings are : ['gfg', 'is', 'for']


方法 #2:使用 filter() + lambda
上述功能的组合可用于执行此任务。在此,我们使用 filter() 提取元素,并在 lambda函数中编译逻辑。

Python3

# Python3 code to demonstrate working of
# Range length Strings extraction
# using filter() + lambda
 
# initialize list
test_list = ['gfg', 'is', 'best', 'for', 'geeks']
 
# printing original list
print("The original list : " + str(test_list))
 
# initialize i, j
i, j = 2, 3
 
# Range length Strings extraction
# using filter() + lambda
res = list(filter(lambda ele: len(ele) >= i and len(ele) <= j, test_list))
 
# printing result
print("The range sized strings are : " + str(res))
输出 :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The range sized strings are : ['gfg', 'is', 'for']