📜  Python – 最大 K 长度的字符串

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

Python – 最大 K 长度的字符串

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

Python3
# Python3 code to demonstrate working of
# Extract Strings with Maximum K length
# 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 Strings with Maximum K length
# using list comprehension + len()
res = [ele for ele in test_list if len(ele) <= K]
 
# printing result
print("The maximum K sized strings are : " + str(res))


Python3
# Python3 code to demonstrate working of
# Extract Strings with Maximum K length
# 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 Strings with Maximum K length
# using filter() + lambda
res = list(filter(lambda ele: len(ele) <= K, test_list))
 
# printing result
print("The maximum K sized strings are : " + str(res))


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


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

Python3

# Python3 code to demonstrate working of
# Extract Strings with Maximum K length
# 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 Strings with Maximum K length
# using filter() + lambda
res = list(filter(lambda ele: len(ele) <= K, test_list))
 
# printing result
print("The maximum K sized strings are : " + str(res))
输出 :
The original list : ['gfg', 'is', 'best', 'for', 'geeks']
The maximum K sized strings are : ['gfg', 'is', 'for']