How to compare two lists in python, but part of the values

Question:

For example lest say I have those two lists:

x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
y = ["hi", "apple"]

How can I tell if all of list y is inside of list x?

Asked By: Liad

||

Answers:

You need to use any and all.

# First check each element of 'y' exist in at least one element of  'x'
>>> [any(i in j for j in x) for i in y]
[True, True]

# Second check all elements of y exist in x.
>>> all(any(i in j for j in x) for i in y) # <- You need this check two steps
True
Answered By: I'mahdi

You can solve this problem in many ways. I will write the most explanatory algorithm but not the more pythonic one.

You can concatenating all elements of the first list into a string and then search whether each element of the second list is contained in the string.

combined = ' '.join(x)

your_bool = False  # init to false
for el in y:
    if el in combined:
        your_bool = True
    else:
        your_bool = False

print(your_bool)
Answered By: Giuseppe La Gualano

Another solution : ly is the list of all elements of y that exists in x elements.

ly={yi for yi in y for xi in x if yi in xi}

now, you can define a bool variable:

are_all_y_elt_in_x_elt = (len(ly)==len(y))

# EX. 1
# x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
# y = ["hi", "apple", "world"]
# 
# are_all_y_elt_in_x_elt = True

# EX. 2
# x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
# y = ["hi", "apple", "worlddd"]
# 
# are_all_y_elt_in_x_elt = False
Answered By: romain gal

If you want to know whether y is a subset of x, then the best approach is to use set operations:

>>> x = ["hi [ICON]", "apple [ICON]", "world [ICON]" ]
... y = ["hi", "apple"]

>>> set(y).issubset(set(x))
False

The reason the result for these is False is because of that [ICON] suffix in each element of x. Example where it is True:

>>> {1,2,3}.issubset({1,2,3,4,5})
True

If you just want to know whether any element of x contains a substring from y, then you could do the following on a per-element basis:

>>> [any(a in word for a in y) for word in x]
[True, True, False]

…or the following for the full check:

>>> all(any(a in word for a in y) for word in x)
False
Answered By: dskrypa
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.