📜  Python – 过滤 K 个子字符串的字符串组合

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

Python – 过滤 K 个子字符串的字符串组合

给定一个字符串列表,提取所有由 K 个子字符串组合而成的字符串。

方法 #1:使用 permutations() + map() + join() + set() + loop

在此,我们通过从子串列表中获取 K 个子串的所有可能排列来执行此任务,然后使用 join 和 map() 执行连接任务。 set() 用于避免重复。最后,使用循环完成字符串列表中的匹配。

Python3
# Python3 code to demonstrate working of 
# Filter Strings  combination of K substrings
# Using permutations() + map() + join() + set() + loop
from itertools import permutations
  
# initializing list
test_list = ["geeks4u", "allbest", "abcdef"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing substring list
substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"]
  
# initializing K 
K = 3
  
# getting all permutations
perms = list(set(map(''.join, permutations(substr_list, r = K))))
  
# using loop to check permutations with list
res = []
for ele in perms:
    if ele in test_list:
        res.append(ele)
  
# printing results 
print("Strings after joins : " + str(res))


Python3
# Python3 code to demonstrate working of 
# Filter Strings  combination of K substrings
# Using permutations() + map() + join() + set() + intersection()
from itertools import permutations
  
# initializing list
test_list = ["geeks4u", "allbest", "abcdef"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing substring list
substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"]
  
# initializing K 
K = 3
  
# getting all permutations
perms = set(map(''.join, permutations(substr_list, r = K)))
  
# using intersection() to solve this problem 
res = list(set(test_list).intersection(perms))
  
# printing results 
print("Strings after joins : " + str(res))


输出
The original list : ['geeks4u', 'allbest', 'abcdef']
Strings after joins : ['geeks4u', 'allbest']

方法#2:使用intersection()

这使用了上述方法的所有功能,匹配排列列表和原始列表的最后一个任务是通过交集完成的。

Python3

# Python3 code to demonstrate working of 
# Filter Strings  combination of K substrings
# Using permutations() + map() + join() + set() + intersection()
from itertools import permutations
  
# initializing list
test_list = ["geeks4u", "allbest", "abcdef"]
  
# printing string
print("The original list : " + str(test_list))
  
# initializing substring list
substr_list = ["s4u", "est", "al", "ge", "ek", "def", "lb"]
  
# initializing K 
K = 3
  
# getting all permutations
perms = set(map(''.join, permutations(substr_list, r = K)))
  
# using intersection() to solve this problem 
res = list(set(test_list).intersection(perms))
  
# printing results 
print("Strings after joins : " + str(res))
输出
The original list : ['geeks4u', 'allbest', 'abcdef']
Strings after joins : ['geeks4u', 'allbest']