Home > front end >  How do I check to see if any value in an array is equal to a different value?
How do I check to see if any value in an array is equal to a different value?

Time:12-06

I was wondering how I could make and if statement to see if any value in a particular array is equal to another value. Instead of me having to do this

if (gray == Span1 and gray == Span2) or (blue == Span1 and blue == Span2) or (gray == Span1 and blue == Span2) or (blue == Span1 and gray == Span2) or (purple == Span1 and purple == Span2) or (purple == Span1 and blue == Span2) or (purple == Span1 and gray == Span2) or (gray == Span1 and purple == Span2) or (blue == Span1 and purple == Span2):

I could do something that would allow me to see if a value like Span1 is equal to gray, blue, or purple, in less code. Something like this ->

colorArray = ["gray","blue","purple"]
if(Span1 == colorArray) or (Span2 == colorArray) or (Span3 == colorArray):
    doThis()
else:
    doSomethingElse()

maybe this will work?

 if (Span1 in colorArray) and (Span2 in colorArray) and (Span3 in colorArray):

CodePudding user response:

You could simplify your code using:

(Span1, Span2) in [('blue', 'blue'), ('blue', 'gray')] # etc. full list of possibilities

But, as you have symmetrical relationships, you could use sets:

{Span1, Span2} in [{'gray', 'gray'}, {'blue', 'blue'}, {'gray', 'blue'}, {'purple', 'purple'}, {'purple', 'blue'}, {'purple', 'gray'}]

Even, better, as you have all combinations, just do:

{Span1, Span2}.issubset(['blue', 'grey', 'purple'])

Example

Span1 = 'blue'
Span2 = 'grey'
Span3 = 'red'

allowed_colors = ['blue', 'grey', 'purple']

if {Span1, Span2}.issubset(allowed_colors):
    print('1 2 OK')

if {Span1, Span3}.issubset(allowed_colors):
    print('1 3 OK')

output:

1 2 OK

CodePudding user response:

Try using a for-loop:

for a in first_list:
    for b in second_list:
        if a == b:
            #do something

CodePudding user response:

If you want to find if any elements in one list appear in another, then I would use a set like so.

def foo(given_list, test_list):
    test_set = set(test_list)
    for element in given_list:
        if element in test_set:
            return True
    return False
A_1 = ['candy', 12, 'thirteen', [], 'blue']
A_2 = ['hand', 15, 'car', 'yellow']
B = ['red', 'green', 'blue']
test_A_1 = foo(A_1, B) # True
test_A_2 = foo(A_2, B) # False

This way, test_A_1 will be True and test_A_2 will be false.

CodePudding user response:

Thank you mozway for showing me this -

if ({Span1, Span2, Span3}.issubset(['pointer gray gray', 'pointer blue blue', 'pointer purple purple'])):
    doSomething()
else:
    pass
  • Related