繁体   English   中英

检查列表中的元素是否存在于python的多个列表中

[英]Check if an element in a list is present in multiple lists in python

我必须检查列表中的元素是否存在于多个列表中。

例:

cornerCase = [-1, 4]
top = [1, 2]
bottom = [2, 3]
left = [-1, 2]
right = [3,1]

在这种情况下,我必须检查顶部,底部,左侧或右侧列表中的任何元素中是否包含-1或4。 寻找更Python化的解决方案。

我的尝试:

1. 
    check = [i for i in cornerCase if i in top or bottom or left or right]

没用 在实现之后or寻找其他表达式。

2.
    check = [i for i in cornerCase if i in (top, bottom, left, right)]

该死的! 没再工作。 有人请解释为什么吗?

3.
    check = [i for i in cornerCase if i in [top, bottom, left, right]]

显然没有用,因为检查列表中的元素。

我检查if check != []然后在那些列表中找到-1 or 4

任何好的pythonic方法来实现这一目标? 不为所有列表寻找具有多个for循环和单个if语句的解决方案。

虽然这可能不是一个很好的解决方案,但它的工作原理很简单,

check = [i for i in cornerCase if i in top + bottom + left + right]

最简单的方法(也许不是太pythonic)是简单地遍历cornerCase并检查其中是否有任何其他列表:

def check(cornerCase, top, left, bottom, right):
  for i in cornerCase:
    if i in top or i in left or i in bottom or i in right:
      return true
  return false

简单方法:对于位于角落的c情况:如果c位于顶部或i位于左侧或i位于底部或i位于右侧:返回true否则返回false

或:List = [corner]中c的List = [top,left,right,bottom]案例:如果List中的c返回true,否则返回false

由于它只是想检查是否存在-14 python中的任何内置函数都会派上用场,并返回True或False。 因此,无需if check != []:

>>> any(item in l for item in cornerCase for l in (top, bottom, left, right))
True

而且Drashan的解决方案也可以正常工作。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM