Python checks whether a character string contains characters in a character set.
Purpose
Checks whether a string contains characters in a character set.
Method
The simplest method is as follows:
Copy codeThe Code is as follows:
Def containAny (seq, aset ):
For c in seq:
If c in aset:
Return True
Return False
The second method is applicable to the itertools module to improve the performance, which is essentially the same method as the former (but this method violates the core idea of Python: concise and clear)
Itertools. ifilter (predicate, iterable) Description
Make an iterator that filters elements from iterable returning only those for which the predicate is True. If predicate is None, return the items that are true.
For example:
Ifilter (lambda x: x % 2, range (10) --> 1 3 5 7 9
Copy codeThe Code is as follows:
Import itertools
Def containAny (seq, aset ):
For item in itertools. ifilter (aset. _ contain __, seq ):
Return True
Return False
If you want to check whether two strings are contained, you must check all the sub-items. It is best to apply the set type, where set (aset ). difference (seq) is an element that exists in aset and does not exist in seq:
Copy codeThe Code is as follows:
Def containAll (seq, aset ):
Return not set (aset). difference (seq)
For example:
Copy codeThe Code is as follows:
In [4]: L1 = [1, 2, 4]
In [5]: L2 = [1, 4, 3, 1]
In [6]: containAll (L1, L2)
Out [6]: True
In [7]: containAll (L2, L1)
Out [7]: False
Note that set. effecric_difference refers to the unique elements of two sets.
Copy codeThe Code is as follows:
In [9]: L2 = [3, 2, 4, 5]
In [10]: x = set (L1)
In [11]: x. symmetric_difference (L2)
Out [11]: set ([1, 5])