简体   繁体   中英

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

I have to check if an element in list is present in multiple list.

Example:

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

In this case I have to check if -1 or 4 is present in any of the elements in top, bottom, left or right lists. Looking for a solution in more pythonic way.

My attempts:

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

Didn't work. Realized after or it looks for other expression.

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

Damn! Didn't work again. Anyone please explain why ?

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

Obviously didn't work because checking a element in a list of lists.

I check if check != [] then -1 or 4 was found in those lists.

Any good pythonic way to achieve this ? Not looking for a solution with multiple for loops and individual if statements for all the lists.

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

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

The easiest way (and maybe not way too pythonic) is to simple iterate over cornerCase and check if any of these are in any of the other lists:

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

Easy way: for c in cornerCase: if c in top or i in left or i in bottom or i in right: return true else return false

OR: List=[top,left,right,bottom] for c in cornerCase: if c in List return true else return false

As its just wanted to just check if -1 or 4 is present. any builtin function in python comes handy and returns True or False. So there won't be any need of if check != []:

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

And Drashan's solution also works fine.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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