📌  相关文章
📜  Python - 查找作为给定字符串列表的子字符串的所有字符串

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

Python - 查找作为给定字符串列表的子字符串的所有字符串

鉴于两个列表,任务是编写Python程序提取所有这些都是可能的子任何在另一个列表字符串的字符串。

例子:

方法#1:使用列表理解

在此,我们执行使用嵌套循环和使用列表推导测试的任务,如果字符串是其他列表的任何子字符串的一部分,则提取该字符串。

Python3
# Python3 code to demonstrate working of
# Substring Intersections
# Using list comprehension
  
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# using list comprehension for nested loops
res = list(
    set([ele1 for sub1 in test_list1 for ele1 in test_list2 if ele1 in sub1]))
  
# printing result
print("Substrings Intersections : " + str(res))


Python3
# Python3 code to demonstrate working of
# Substring Intersections
# Using any() + generator expression
  
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# any() returns the string after match in any string
# as Substring
res = [ele2 for ele2 in test_list2 if any(ele2 in ele1 for ele1 in test_list1)]
  
# printing result
print("Substrings Intersections : " + str(res))


输出:

方法#2:使用 any() + 生成器表达式

在这里, any() 用于检查要匹配的字符串列表中的任何字符串中的子字符串匹配。

蟒蛇3

# Python3 code to demonstrate working of
# Substring Intersections
# Using any() + generator expression
  
# initializing lists
test_list1 = ["Geeksforgeeks", "best", "for", "geeks"]
test_list2 = ["Geeks", "win", "or", "learn"]
  
# printing original lists
print("The original list 1 is : " + str(test_list1))
print("The original list 2 is : " + str(test_list2))
  
# any() returns the string after match in any string
# as Substring
res = [ele2 for ele2 in test_list2 if any(ele2 in ele1 for ele1 in test_list1)]
  
# printing result
print("Substrings Intersections : " + str(res))

输出: