📜  Python – 长度条件连接

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

Python – 长度条件连接

给定一个字符串列表,执行长度大于 K 的字符串的连接。

方法 #1:使用循环 + len()

这提供了解决这个问题的蛮力方法。在此,我们对每个字符串进行迭代,如果字符串长度大于 K,则使用 len() 执行连接。

Python3
# Python3 code to demonstrate working of 
# Length Conditional Concatenation
# Using loop + len()
  
# initializing lists
test_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 2
  
# loop to run through all the elements
res = ''
for ele in test_list:
      
    # using len() to check for length
    if len(ele) > 2:
        res += ele
  
# printing result 
print("String after Concatenation : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Length Conditional Concatenation
# Using join() + filter() + lambda + len()
  
# initializing lists
test_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 2
  
# join() performing Concatenation of required strings
res = ''.join(filter(lambda ele: len(ele) > K, test_list))
  
# printing result 
print("String after Concatenation : " + str(res))


输出
The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']
String after Concatenation : GfgBestforEverything

方法 #2:使用 join() + filter() + lambda + len()

上述功能的组合可以用来解决这个问题。在此,我们使用 join() 执行连接,filter 和 lambda 用于使用 len() 进行条件检查。

Python3

# Python3 code to demonstrate working of 
# Length Conditional Concatenation
# Using join() + filter() + lambda + len()
  
# initializing lists
test_list = ["Gfg", 'is', "Best", 'for', 'CS', 'Everything']
  
# printing original list
print("The original list : " + str(test_list))
  
# initializing K 
K = 2
  
# join() performing Concatenation of required strings
res = ''.join(filter(lambda ele: len(ele) > K, test_list))
  
# printing result 
print("String after Concatenation : " + str(res))
输出
The original list : ['Gfg', 'is', 'Best', 'for', 'CS', 'Everything']
String after Concatenation : GfgBestforEverything