📜  Python|从元组列表中查找包含给定元素的元组

📅  最后修改于: 2022-05-13 01:55:03.318000             🧑  作者: Mango

Python|从元组列表中查找包含给定元素的元组

给定一个元组列表,任务是找到所有包含给定元素的元组,比如n
例子:

有多种方法可以从元组列表中找到包含给定元素的元组。让我们看看一些 Pythonic 方法来完成这项任务。
方法#2:使用列表推导。它仅在每个列表中有固定数量的元素时才有效。例如下面代码中的 2 个元素。

Python3
# Python code to find the tuples containing
# the given element from a list of tuples
 
# List of tuples
Input = [(14, 3),(23, 41),(33, 62),(1, 3),(3, 3)]
 
# Find an element in list of tuples.
Output = [item for item in Input
          if item[0] == 3 or item[1] == 3]
 
# printing output
print(Output)


Python3
# Python code to find the tuples containing
# the given element from a list of tuples
 
# List of tuples
Input = [(11, 22), (33, 55), (55, 77),
         (11, 44), (33, 22, 100, 11), (99, 11)]
 
# Using filter
Output = list(filter(lambda x:11 in x, Input))
 
# Printing output
print(Output)


输出:
[(14, 3), (1, 3), (3, 3)]


方法#1:使用过滤器在这个解决方案中,列表中可以有可变数量的节点。

Python3

# Python code to find the tuples containing
# the given element from a list of tuples
 
# List of tuples
Input = [(11, 22), (33, 55), (55, 77),
         (11, 44), (33, 22, 100, 11), (99, 11)]
 
# Using filter
Output = list(filter(lambda x:11 in x, Input))
 
# Printing output
print(Output)
输出:
[(11, 22), (11, 44), (33, 22, 100, 11), (99, 11)]