Python Cookbook 1.8 判断字符串内是否包含指定集合的字符

本文介绍如何使用Python判断字符串是否包含指定字符集合中的任一字符、所有字符或仅这些字符的方法。通过不同函数实现,包括循环迭代、迭代工具及集合运算等。
问题:

给定一个字符集合,需要判断在特定字符串内,是否包含该集合的字符.

解决方法:

最简单,直观,效率最高的算法就是使用循环迭代.而且还具有通用性,不仅适用与字符串,也适用与其它序列.

def containsAny(seq, aset):
""" Check whether sequence seq contains ANY of the items in aset. """
for c in seq:
if c in aset: return True
return False

当然,也可以使用更高级的办法,用Python提供的迭代工具:

import itertools
def containsAny(seq, aset):
for item in itertools.ifilter(aset._ _contains_ _, seq):
return True
return False

另:对于和集合相关的问题,都可以使用集合来解决.对于我们需求,可以使用下面的方式来实现:

def containsAny(seq, aset):
return bool(set(aset).intersection(seq))

这个方法返回了两个集合的交集,也就是说,两个集合中所有的元素都进行了判断,从效率上讲,没有上面提供的两种方法好.
然而,如果需求是需要判断集合内的字符是否都包含在字符串内,使用集合提供的方法会更方便一些:

def containsAll(seq, aset):
""" Check whether sequence seq contains ALL the items in aset. """
return not set(aset).difference(seq)

如果需求是判读字符串内是否只包含集合内的字符,可以用下面的算法:

def containsOnly(seq, aset):
""" Check whether sequence seq contains ONLY items in aset. """
for c in seq:
if c not in aset: return False
return True

相关说明:

intersection(...)
Return the intersection of two sets as a new set.

(i.e. all elements that are in both sets.)

difference(...)
Return the difference of two sets as a new set.

(i.e. all elements that are in this set but not the other.)
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值