列表与字符串中的“in”语句行为

2024-05-14 16:42:52 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python中,询问字符串中是否存在子字符串非常简单:

>>> their_string = 'abracadabra'
>>> our_string = 'cad'
>>> our_string in their_string
True

但是,检查这些相同的字符是否“在”列表中失败:

>>> ours, theirs = map(list, [our_string, their_string])
>>> ours in theirs
False
>>> ours, theirs = map(tuple, [our_string, their_string])
>>> ours in theirs
False

我找不到任何明显的原因来解释为什么在一个有序的(甚至是不可变的)iterable中检查元素的行为与另一个不同类型的有序的、不可变的iterable不同。你知道吗


Tags: 字符串infalsetruemapstringouriterable
3条回答

你想看看“cad”是否在字符串列表中的任何字符串中吗?它会像这样:

stringsToSearch = ['blah', 'foo', 'bar', 'abracadabra']
if any('cad' in s for s in stringsToSearch):
    # 'cad' was in at least one string in the list
else:
    # none of the strings in the list contain 'cad'

对于列表和元组等容器类型,x in container检查x是否是容器中的项。因此,使用ours in theirs,Python检查ours是否是theirs中的项,并发现它是False。你知道吗

记住,列表可以包含一个列表。(例如[['a','b','c'], ...]

>>> ours = ['a','b','c']    
>>> theirs = [['a','b','c'], 1, 2]    
>>> ours in theirs
True

在Python文档中,https://docs.python.org/2/library/stdtypes.html对于序列:

x in s  True if an item of s is equal to x, else False  (1)
x not in s  False if an item of s is equal to x, else True  (1)

(1) When s is a string or Unicode string object the in and not in operations act like a substring test.

对于用户定义的类,__contains__方法实现这个in测试。listtuple实现了基本概念。string增加了“substring”的概念。string是基本序列中的一个特例。你知道吗

相关问题 更多 >

    热门问题