How do you compare elements of a list with a nested list?

71 Views Asked by At
a = [[1, 3, 4],[1, 7, 9]]]
b = [1, 7, 0, 9]

Let's say I have a nested list of a, I want to compare the list of b to the nested list a and return True. Say b has 3 items that matches with one of the lists in a, that would be True. How do I do this?

the prompt was to create a tic tac toe game. List a has all the winning combinations, while list b are all the player input. If input is contains 1, 7, and 9 (as in list b), then the combination is part of the winning combinations (in list a). However, player input could include more than 3 numbers and not in the combination order in list a.

I tried the below:

a = [[1, 3, 4],[1,7,9]]
b = [1, 7, 0, 9]
set(a).issubset(b)

But clearly it did not work.

4

There are 4 best solutions below

5
OysterShucker On

If you want to check if the all of the contents of a sublist of a are in b, you can use a set and check the difference.

compare = [[1, 3, 4],[1, 7, 9]]
moves   = [1, 7, 0, 9]

def check(a:list[list], b:list) -> bool:
    y = set(b)
    return any(not (x-y) for x in map(set, a))
    
print(check(compare, moves))
0
deceze On

You want to check for each individual list in a whether it's a subset of b. If that's the case for any one, the result is true:

a = [[1, 3, 4], [1, 7, 9]]
b = [1, 7, 0, 9]

b = set(b)
print(any(set(i) <= b for i in a))
1
alec_djinn On

Building from what you have tried, I think you want to do the following:

a = [[1, 3, 4],[1,7,9]]
b = [1, 7, 0, 9]

for item in a:
    if set(item).issubset(b):
        print(item, 'is subset of', b)

or in general, if you want to check if any item of a is a subset of b:

any(set(item).issubset(b) for item in a)
0
no comment On

Using superset:

a = [[1, 3, 4], [1, 7, 9]]
b = [1, 7, 0, 9]

print(any(map(set(b).issuperset, a)))

Attempt This Online!