Python detects whether a character in a character set is included in a string

Source: Internet
Author: User
Purpose

Detects if a character in a character set is contained in a string

Method

The simplest method is as follows, clear, universal, fast, suitable for any sequence and container

Copy the Code code as follows:


def containany (Seq,aset):
For C in SEQ:
If C in Aset:
Return True
Return False


The second applies to the Itertools module to improve a bit of performance, essentially the same way as the former (although this approach violates Python's core point of view: concise, clear)

Description of Itertools.ifilter (predicate, iterable)

Make a iterator that filters elements from iterable returning only those for which the predicate is True. IF predicate is None, return the items ' is true.

For example:

IFilter (Lambda x:x%2, Range)--1 3 5 7 9

Copy the Code code 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 inclusive, you must check all subkeys at this point, preferably the set type, where set (Aset). Difference (seq) is an element that exists in aset and that SEQ does not:
Copy the Code code as follows:


def containall (Seq,aset):
Return not set (Aset). difference (seq)

For example, the following example:

Copy the Code code 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 two unique elements of a collection
Copy the Code code as follows:


In [9]: l2=[3,2,4,5]
In [ten]: X=set (L1)
In [All]: X.symmetric_difference (L2)
OUT[11]: Set ([1, 5])
  • Contact Us

    The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

    If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.