如何在python中检查列表列表中是否存在值?

如何在python中检查列表列表中是否存在值?,python,list,Python,List,我有一份清单: lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]] 我想检查列表中是否存在一个值,例如67。我已经看过StackOverflow问题: 但它只显示了一种检查值是否在列表列表中的方法 无论列表有多深,我如何搜索列表?如果列表不大,您需要简单的解决方案,则可以将列表转换为字符串,并检查该字符串中数字的字符串值参见下面的示例: lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]] lst1 = str

我有一份清单:

lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
我想检查列表中是否存在一个值,例如67。我已经看过StackOverflow问题:

但它只显示了一种检查值是否在列表列表中的方法


无论列表有多深,我如何搜索列表?

如果列表不大,您需要简单的解决方案,则可以将列表转换为字符串,并检查该字符串中数字的字符串值参见下面的示例:

lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
lst1 = str(lst)
print(lst)
print(str(67) in lst1)
输出为:

[[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]
True

如果您的列表不大,并且需要简单的解决方案,则可以将列表转换为字符串,并检查该字符串中数字的字符串值。请参见下面的示例:

lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
lst1 = str(lst)
print(lst)
print(str(67) in lst1)
输出为:

[[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]
True
递归地

from typing import List, Tuple, Any, Union

RecursiveList = Union[List['RecursiveList'], Any]

def multiindex(lst: List[RecursiveList], item) -> Tuple[int]:
    for idx, elem in enumerate(lst):
        if elem == item:
            return (idx,)
        else:
            # try to call it recursively. 
            # if the current element isn't iterable, enumerate() will throw a TypeError
            # which we can just ignore
            try:
                return (idx,) + multiindex(elem, item)
            except (TypeError, ValueError):
                continue
    raise ValueError(f'{item} is not in list')

l = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
print(multiindex(l, 67))
# (1, 1, 3, 1)
我们可以通过简单地检查搜索时是否得到ValueError来测试是否包含,就像我们使用普通的
list.index()
一样。或者,只需修改方法以返回布尔值,而不是抛出
ValueError

def multicontains(lst: List[RecursiveList], item) -> bool:
    for idx, elem in enumerate(lst):
        if elem == item:
            return True
        else:
            try:
                sublist_contains = multicontains(elem, item)
                if sublist_contains:
                    return True
            except TypeError:
                continue
    return False
递归地

from typing import List, Tuple, Any, Union

RecursiveList = Union[List['RecursiveList'], Any]

def multiindex(lst: List[RecursiveList], item) -> Tuple[int]:
    for idx, elem in enumerate(lst):
        if elem == item:
            return (idx,)
        else:
            # try to call it recursively. 
            # if the current element isn't iterable, enumerate() will throw a TypeError
            # which we can just ignore
            try:
                return (idx,) + multiindex(elem, item)
            except (TypeError, ValueError):
                continue
    raise ValueError(f'{item} is not in list')

l = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
print(multiindex(l, 67))
# (1, 1, 3, 1)
我们可以通过简单地检查搜索时是否得到ValueError来测试是否包含,就像我们使用普通的
list.index()
一样。或者,只需修改方法以返回布尔值,而不是抛出
ValueError

def multicontains(lst: List[RecursiveList], item) -> bool:
    for idx, elem in enumerate(lst):
        if elem == item:
            return True
        else:
            try:
                sublist_contains = multicontains(elem, item)
                if sublist_contains:
                    return True
            except TypeError:
                continue
    return False

除了将列表转换为字符串外,还可以在展开列表中搜索该项

要使列表变得平坦,我们可以使用
collections.abc
中的类

from collections.abc import Iterable


def get_flatten(ar):
  if isinstance(ar, Iterable):
    return [inner_iterable for i in ar for inner_iterable in get_flatten(i)]
  return [ar]

def get_searched_result(ar, item):
  return item in get_flatten(ar)


if __name__ == "__main__":
  lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
  item = 67
  print(f"{item} in {lst}: {get_searched_result(lst, item)}")


  item = 32
  print(f"{item} in {lst}: {get_searched_result(lst, item)}")
输出:

67 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: True
32 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: False
参考文献:

67 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: True
32 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: False

除了将列表转换为字符串外,您还可以在展开列表中搜索该项

要使列表变得平坦,我们可以使用
collections.abc
中的类

from collections.abc import Iterable


def get_flatten(ar):
  if isinstance(ar, Iterable):
    return [inner_iterable for i in ar for inner_iterable in get_flatten(i)]
  return [ar]

def get_searched_result(ar, item):
  return item in get_flatten(ar)


if __name__ == "__main__":
  lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]]]
  item = 67
  print(f"{item} in {lst}: {get_searched_result(lst, item)}")


  item = 32
  print(f"{item} in {lst}: {get_searched_result(lst, item)}")
输出:

67 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: True
32 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: False
参考文献:

67 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: True
32 in [[[1, 2, 3], [3, 4, 5]], [1, [2, 34, 5, [45, 67]]]]: False

    • 另一种无需任何库的递归方式,用于嵌套列表。一旦找到值,它就会返回

      def find_nested(lst, val):
        if val in lst:
          return True
        for e in lst:
          if e.__class__ == list and find_nested(e, val):
            return True
        return False
      
      例如:

      lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]],1]
      
      find_nested(lst, 1) #=> True --- it returns at first call
      find_nested(lst, 67) #=> True
      find_nested(lst, 670) #=> False
      
      find_nested(lst, [3,4,5]) #=> True
      

      您可以编辑该方法,使其也返回找到该值的列表。或者让它去检查所有嵌套列表,返回包含元素的每个列表。或者任何您需要的行为。

      另一种无需任何嵌套列表库的递归方式。一旦找到值,它就会返回

      def find_nested(lst, val):
        if val in lst:
          return True
        for e in lst:
          if e.__class__ == list and find_nested(e, val):
            return True
        return False
      
      例如:

      lst = [[[1,2,3],[3,4,5]],[1,[2,34,5,[45,67]]],1]
      
      find_nested(lst, 1) #=> True --- it returns at first call
      find_nested(lst, 67) #=> True
      find_nested(lst, 670) #=> False
      
      find_nested(lst, [3,4,5]) #=> True
      

      您可以编辑该方法,使其也返回找到该值的列表。或者让它去检查所有嵌套列表,返回包含元素的每个列表。或者你需要的任何行为。

      这能回答你的问题吗?这回答了你的问题吗?不推荐。对于任何包含67的内容,都会返回True。167267671。不推荐。对于任何包含67的内容,都会返回True。167267671.我得到了“回溯(最近一次调用):文件“/prog.py”,在NameError中的第3行:当我运行此命令时,名称“Union”未定义。@sasindumaheepala抱歉,忘记从键入中导入
      Union
      。固定的。如果需要,您可以删除注释,它们只是为了清晰起见。当我运行此操作时,我得到了“回溯(最近一次调用):文件“/prog.py”,第3行,在NameError中:名称“Union”未定义。@sasindumaheepala抱歉,忘记从键入中导入
      Union
      。固定的。如果需要,您可以删除注释,它们只是为了清晰起见。我会小心使用
      e.\uu class\uuu==list
      isinstance(e,list)
      ,因为还有其他类型的iterable,比如
      tuple
      s,如果您希望这种代码能够工作,那么就不要使用
      e.\uuu class\uuu==list
      isinstance(e,list)
      ,因为您希望这种代码可以使用其他类型的iterable,比如
      tuple
      s