在 Python 中刪除匹配的元組
當需要從兩個元組列表中刪除匹配的元組時,可以使用列表推導。
一個列表可以用來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。
一個元組列表本質上包含一個包含在列表中的元組。
列表推導是對列表進行迭代並在其上執行操作的簡寫。
下面是一個關於相同情況的演示 −
示例
my_list_1 = [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')] my_list_2 = [('Hi', 'there'), ('Hi', 'Jane')] print("The first list is : ") print(my_list_1) print("The second list is : ") print(my_list_2) my_result = [sub for sub in my_list_1 if sub not in my_list_2] print("The filtered out list of tuples is : ") print(my_result)
輸出
The first list is : [('Hi', 'there'), ('Jane', 'Hi'), ('how', 'are'), ('you', '!')] The second list is : [('Hi', 'there'), ('Hi', 'Jane')] The filtered out list of tuples is : [('Jane', 'Hi'), ('how', 'are'), ('you', '!')]
解釋
- 定義了兩個元組列表,並顯示在控制檯上。
- 使用列表推導來遍歷元組。
- 這將過濾出同時存在於兩個元組列表中的元組。
- 剩下的內容顯示在控制檯上。
廣告