Python checks whether a string contains characters in a character set.
This article mainly introduces whether the Python check string contains characters in a character set. For more information, see
Purpose
Checks whether a string contains characters in a character set.
Method
The simplest method is as follows:
The 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
The 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:
The Code is as follows:
Def containAll (seq, aset ):
Return not set (aset). difference (seq)
For example:
The 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.
The 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])