發現 Python 中元組列表中包含給定元素的元組
列表的元素可以是元組。本文我們將瞭解如何識別包含特定搜尋元素(字串)的元組。
使用 in 和條件
我們可以設計帶有 in 條件的後續內容。在 in 之後,我們可提及條件或條件組合。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng for and if
res = [item for item in listA
if item[0] == test_elem and item[1] >= 2]
# printing res
print("The tuples satisfying the conditions:\n ",res)輸出
執行以上程式碼,會產生以下結果 −
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]使用 filter
我們使用 filter 函式和 Lambda 函式。在 filter 條件中,我們使用 in 運算子來檢查元組中是否存在該元素。
示例
listA = [('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
test_elem = 'Mon'
#Given list
print("Given list:\n",listA)
print("Check value:\n",test_elem)
# Uisng lambda and in
res = list(filter(lambda x:test_elem in x, listA))
# printing res
print("The tuples satisfying the conditions:\n ",res)輸出
執行以上程式碼,會產生以下結果 −
Given list:
[('Mon', 3), ('Tue', 1), ('Mon', 2), ('Wed', 3)]
Check value:
Mon
The tuples satisfying the conditions:
[('Mon', 3), ('Mon', 2)]
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
JavaScript
PHP