Python - 查詢所有是給定的字串列表的子字串的字串
當需要找到所有給定字串列表的子字串的字串時,使用“set”和“list”屬性。
示例
以下是對其進行演示
my_list_1 = ["Hi", "there", "how", "are", "you"] my_list_2 = ["Hi", "there", "how", "have", "you", 'been'] print("The first list is :") print(my_list_1) print("The second list is :") 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("The result is :") print(my_result)
輸出
The first list is : ['Hi', 'there', 'how', 'are', 'you'] The second list is : ['Hi', 'there', 'how', 'have', 'you', 'been'] The result is : ['there', 'you', 'Hi', 'how']
解釋
定義了兩個字串列表,並在控制檯上顯示它們。
迭代這兩個列表,並使用“set”屬性來獲取列表中的唯一值。
現在將此轉換為列表。
這被分配給一個變數。
這是顯示在控制檯上的輸出。
廣告