This article mainly describes whether the python detection string contains characters in a character set, the need for friends can refer to the following
Objective
Detects whether characters in a character set are included in a string
Method
The most concise method is the following, clear, universal, fast, applicable to any sequence and container
The code is as follows:
def containany (Seq,aset):
For C in SEQ:
If C in Aset:
Return True
Return False
The second application of the Itertools module to improve performance is essentially the same method as the former (although this approach violates Python's core view: simplicity, clarity)
Description of Itertools.ifilter (predicate, iterable)
Make a iterator that filters elements to iterable returning only those to which the predicate is True. IF predicate is None, return the items that are true.
For example:
IFilter (Lambda x:x%2, Range ())--> 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 detect whether two strings are included, you must check all the subkeys, preferably the set type, where set (Aset). Difference (seq) is an element that is present in aset but not in seq:
The code is as follows:
def containall (Seq,aset):
Return not set (Aset). difference (seq)
For example, the following example:
The code is as follows:
In [4]: l1=[1,2,3,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.symmetric_difference refers to elements unique to two collections
The code is as follows:
In [9]: l2=[3,2,4,5]
In [ten]: X=set (L1)
In [one]: x.symmetric_difference (L2)
OUT[11]: Set ([1, 5])