检查一个项目是否在嵌套列表中

新手上路,请多包涵

在一个简单的列表中,以下检查是微不足道的:

 x = [1, 2, 3]

2 in x  -> True

但是如果是list of list,比如:

 x = [[1, 2, 3], [2, 3, 4]]

2 in x   -> False

如何解决这个问题才能返回 True

原文由 Al_Iskander 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 318
2 个回答

试试这个,使用内置的 any 功能。这是最惯用的解决方案,它也很有效,因为 any 一旦找到第一个匹配项就会短路并停止:

 x = [[1, 2, 3], [2, 3, 4]]
any(2 in sl for sl in x)
=> True

原文由 Óscar López 发布,翻译遵循 CC BY-SA 3.0 许可协议

这是适用于任何嵌套级别的递归版本。

 def in_nested_list(my_list, item):
    """
    Determines if an item is in my_list, even if nested in a lower-level list.
    """
    if item in my_list:
        return True
    else:
        return any(in_nested_list(sublist, item) for sublist in my_list if isinstance(sublist, list))

这里有一些测试:

 x = [1, 3, [1, 2, 3], [2, 3, 4], [3, 4, [], [2, 3, 'a']]]
print in_nested_list(x, 2)
print in_nested_list(x, 5)
print in_nested_list(x, 'a')
print in_nested_list(x, 'b')
print in_nested_list(x, [])
print in_nested_list(x, [1, 2])
print in_nested_list(x, [1, 2, 3])

True
False
True
False
True
False
True

原文由 Curt F. 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题