What would be the fastest to iterate list x
to check if any of its characters are listed in y
?
x=['cat','dog','fish']
y=['a','b','b']
What would be the fastest to iterate list x
to check if any of its characters are listed in y
?
x=['cat','dog','fish']
y=['a','b','b']
You can convert y
to a set and then iterate over x
to see if any of y
is in it, like this
print any(any(item in word for word in x) for item in set(y))
# True
any
short-circuits immediately after finding a match, so this would be very efficient.
Apart from that we can convert both of them to sets, and then check if they are disjoint sets, like this
print not {char for word in x for char in word}.isdisjoint(set(y))
# True
isdisjoint
also short-circuits if it determines that both the sets are not disjoint sets.
Use list comprehension:
>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> [char in word for char in y for word in x]
[True, False, False, False, False, False, False, False, False]
>>>
This prints the above output for all the characters and words: True
because 'a'
is in 'cat'
, and False
for the rest, because nothing else exists.
Here is an example that is easier to read:
>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> [(word, char, char in word) for char in y for word in x]
[('cat', 'a', True), ('dog', 'a', False), ('fish', 'a', False), ('cat', 'b', False), ('dog', 'b', False), ('fish', 'b', False), ('cat', 'c', True), ('dog', 'c', False), ('fish', 'c', False)]
>>> ["It is %s that %s is in %s" %(str(char in word), char, word) for char in y for word in x]
['It is True that a is in cat', 'It is False that a is in dog', 'It is False that a is in fish', 'It is False that b is in cat', 'It is False that b is in dog', 'It is False that b is in fish', 'It is True that c is in cat', 'It is False that c is in dog', 'It is False that c is in fish']
>>>
Answering your comment, yes there is way:
>>> x = ['cat', 'dog', 'fish']
>>> y = ['a', 'b', 'c']
>>> myList = []
>>> [myList.append(word) for word in x for char in y if char in word]
[None, None]
>>> myList
['cat', 'cat']
>>> list(set(myList))
['cat']
>>>
The reason why the list comprehension prints [None, None]
is because the built-in method append()
doesn't return anything, hence the None
.
why isn't this enough for comparison?
>>> x=['cat','dog','fish']
>>> y=['a','b','b']
>>> x == y
False
>>> b = ['a','b', 'b']
>>> x == b
False
>>> y == b
True