AnswerBun.com

Comparing two lists for same value

Stack Overflow Asked by Sebaku on November 22, 2020

Let’s say I have 3 lists:

a = [0,0,0,1,1]
b = [1,0,0,0,0]
c = [1,1,1,0,0]

I want to return False whenever there are 1’s at the same position, so for ‘b & c’ it would return False, because they both have a one at index 0, ‘a & b’ and ‘a & c’ should return True in this case.

The way I would do it is:

for i in range(0, len(a)):
   if a[i] == 1 and b[i] == 1:
      return False
return True

Though I feel this is very inefficient. Is there an easier and more efficient way to do this? I was thinking of using binary AND, but not sure how to implement that.

One Answer

Are you looking for one liner. Here it is:

any([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])

Sorry did not test it. Here is modified version with test:

>>> a = [0,0,0,1,1]
>>> b = [1,0,0,0,0]
>>> c = [1,1,1,0,0]
>>> def f(a,b):
...   return all([False if a[i] == 1 and b[i] == 1 else True for i in range(0, len(a))])
...
>>> print(f(a,b), f(b,c), f(a,c))
True False True

Answered by Aaj Kaal on November 22, 2020

Add your own answers!

Related Questions

Remove item from state

3  Asked on December 5, 2020 by clayton-crockville

 

How to concatenate 3 lists even if there are a list null?

2  Asked on December 5, 2020 by alexz

       

Angular 8: Select first element of ng-content

1  Asked on December 5, 2020 by ijustdev

     

docker-compose volume empty

3  Asked on December 5, 2020 by kerby82

   

Extract value of column from a line (variable)

4  Asked on December 4, 2020 by user4516211

       

Merge Two Files in Weka based on date

1  Asked on December 4, 2020 by spwath

 

Set Session ID Cookie in Nuxt Auth

1  Asked on December 4, 2020 by dominooch

   

Warnings in gcc compiler

1  Asked on December 3, 2020 by hygor-marques

     

Ask a Question

Get help from others!

© 2022 AnswerBun.com. All rights reserved. Sites we Love: PCI Database, MenuIva, UKBizDB, Menu Kuliner, Sharing RPP, SolveDir