Pol Porta
Pol Porta

Reputation: 21

How to determine if a list with duplicates is contained in another list also with duplicates

I want to compare 2 lists to know if one contains some elements of the other. Here's an example:

contents = ['blue', 'blue', 'blue', 'red', 'red', 'green']
expected = ['blue', 'blue', 'red']

if expected in contents:
    return True
else:
    return False

I would like that code to return True. But for example if I use:

expected = ['red', 'green', 'green']

That should return False 'cause there's only one green on the contents.

Upvotes: 1

Views: 73

Answers (4)

Pol Porta
Pol Porta

Reputation: 21

def colors():
    for x in expected:
        if x in contents:
            contents.remove(x)
            if x in contents:
                good.append(x)
    if len(good) == len(expected):
        return True
    else:
        return False
print(colors())

Upvotes: 0

Tom
Tom

Reputation: 8800

I think you could use a collections.Counter here, (inspired by this answer). Get a count of the unique elements in expected and contents, then loop over the items in expected to make sure count in contents is at least as much.

from collections import Counter

contents = ['blue', 'blue', 'blue', 'red', 'red', 'green']
expected = ['blue', 'blue', 'red']

a = Counter(contents)
b = Counter(expected)

print(all([a[k] >= b[k] for k in b.keys()]))
# True

c = Counter(['red', 'green', 'green'])
print(all([a[k] >= c[k] for k in c.keys()])) # c instead of b
# False

Functional form:

def list_inside(contents, expected):
    contents = Counter(contents)
    expected = Counter(expected)
    return all([contents[k] >= expected[k] for k in expected.keys()])

Upvotes: 0

Sven Eberth
Sven Eberth

Reputation: 3116

This should work, even for duplicates:

def contains(haystack, needle):
    haystack = haystack.copy()
    for item in needle:
        if item not in haystack:
            return False
        haystack.remove(item)
    return True


contents = ['blue', 'blue', 'blue', 'red', 'red', 'green']
print(contains(contents, ['blue', 'blue', 'red']))
# True
print(contains(contents, ['red', 'green', 'green']))
# False

Upvotes: 1

user15801675
user15801675

Reputation:

Here is a small code piece.

contents = ['blue', 'blue', 'blue', 'red', 'red', 'green']
expected = ['blue', 'blue', 'red']
new_colours =[x for x in expected if x in contents] #=== Check if the value in contents
print(new_colours)

Output:

['blue', 'blue', 'red']

Here, I change expectedlist

expected=['blue','blue','yellow']

Output:

['blue', 'blue']

Upvotes: 0

Related Questions