Python - 查找给定字符串列表中所有子字符串

pythonserver side programmingprogramming更新于 2025/11/9 23:08:17

当需要查找给定字符串列表中所有子字符串时,‘set’ 和 ‘list’属性被使用。

示例

下面是相同的演示

my_list_1 = ["Hi", "there", "how", "are", "you"]
my_list_2 = ["Hi", "there", "how", "have", "you", 'been']
print("第一个列表是:")
print(my_list_1)
print("第二个列表是:")
print(my_list_2)

my_result = list(set([elem_1 for subset_1 in my_list_1 for elem_1 in my_list_2 if elem_1 in subset_1]))

print("结果为:")
print(my_result)

输出

第一个列表是:
['Hi', 'there', 'how', 'are', 'you']
第二个列表是:
['Hi', 'there', 'how', 'have', 'you', 'been']
结果为:
['there', 'you', 'Hi', 'how']

解释

  • 定义了两个字符串列表,并将它们显示在控制台上。

  • 对两个列表进行迭代,并使用‘set’属性从列表中获取唯一值。

  • 现在将其转换为列表。

  • 这已分配给变量。

  • 这是显示在控制台上的输出。


相关文章


有用资源