根據列表元素存在情況過濾 Python 中的元組
當需要根據存在的列表元素過濾元組時,可以使用列表解析。
可以使用列表來儲存異構值(即任何資料型別的資料,如整數、浮點數、字串等)。
元組列表基本包含列表中括起來的元組。列表解析是遍歷列表並對其執行操作的簡寫。
以下是同樣的演示 −
示例
my_list = [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] target_list = [34, 11] print("The list is : ") print(my_list) my_result = [tup for tup in my_list if any(i in tup for i in target_list)] print("The filtered tuple from the list is: ") print(my_result)
輸出
The list is : [(11, 14), (54, 56, 87), (98, 0, 10), (13, 76)] The filtered tuple from the list is: [(11, 14)]
說明
- 定義了一個元組列表,並在控制檯上顯示。
- 定義了另一個目標列表。
- 根據此目標列表,使用列表解析過濾出原始元組列表。
- 然後將其轉換為元組列表。
- 這被分配給一個值。
- 它在控制檯上顯示。
廣告