检查项目是否在嵌套列表中 [英] Check if an item is in a nested list
本文介绍了检查项目是否在嵌套列表中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在简单检查后的简单列表中很简单:
in a simple list following check is trivial:
x = [1, 2, 3]
2 in x -> True
,但如果是列表列表,例如:
but if it is a list of list, such as:
x = [[1, 2, 3], [2, 3, 4]]
2 in x -> False
如何解决此问题以便返回True
?
how can this be addressed in order to return True
?
推荐答案
使用内置的 any
函数.这是最惯用的解决方案,它也是有效的,因为any
会在找到第一个匹配项后立即短路并停止:
Try this, using the built-in any
function. It's the most idiomatic solution, and it's also efficient, because any
short-circuits and stops as soon as it finds the first match:
x = [[1, 2, 3], [2, 3, 4]]
any(2 in sl for sl in x)
=> True
这篇关于检查项目是否在嵌套列表中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文