📌  相关文章
📜  Python|检查列表列表中是否存在元素(1)

📅  最后修改于: 2023-12-03 15:04:26.481000             🧑  作者: Mango

Python | 检查列表列表中是否存在元素

在 Python 中,我们经常需要检查一个列表列表是否包含某个特定元素。这种操作可以通过遍历列表以及使用内置的 in 操作符来实现。下面是一些用于检查列表列表中是否存在某个元素的方法。

方法1:使用循环和 in 操作符
def is_element_in_list_of_lists(element, list_of_lists):
    for sublist in list_of_lists:
        if element in sublist:
            return True
    return False

该方法通过遍历列表列表中的每个子列表,并使用 in 操作符检查特定元素是否存在于子列表中。如果存在则返回 True,如果整个列表都没有找到该元素,则最终返回 False。

方法2:使用 any() 方法和列表推导式
def is_element_in_list_of_lists(element, list_of_lists):
    return any(element in sublist for sublist in list_of_lists)

使用 any() 方法和列表推导式可以简化上面的代码。列表推导式创建了一个新的布尔值列表,其中每个元素指示特定元素是否存在于对应的子列表中。然后,any() 方法用于检查是否有任何一个布尔值为 True,如果有则返回 True,否则返回 False。

示例
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
element = 5

if is_element_in_list_of_lists(element, list_of_lists):
    print(f"The element {element} is present in the list of lists.")
else:
    print(f"The element {element} is not present in the list of lists.")

上述示例中的 list_of_lists 是一个列表列表,包含三个子列表。我们要检查的元素是 5。程序会调用 is_element_in_list_of_lists() 函数来检查该元素是否存在于列表列表中。根据返回结果,会输出相应的消息。

希望以上信息能对你有所帮助!