gpt4 book ai didi

python - 字符串与列表成员资格检查

转载 作者:太空狗 更新时间:2023-10-29 17:56:12 26 4
gpt4 key购买 nike

所以我想知道为什么会这样:

'alpha' in 'alphanumeric'

True,但是

list('alpha') in list('alphanumeric')

False

为什么当xs的子串时x in s会成功,而x in l却不会当xl 的子列表 时?

最佳答案

当您对任何可迭代对象使用 list 函数时,将创建一个新的列表对象,并将可迭代对象中的所有元素作为列表中的单个元素。

在您的例子中,字符串是有效的 Python 可迭代对象,所以

>>> list('alpha')
['a', 'l', 'p', 'h', 'a']
>>> list('alphanumeric')
['a', 'l', 'p', 'h', 'a', 'n', 'u', 'm', 'e', 'r', 'i', 'c']

因此,您实际上是在检查一个列表是否是另一个列表的子列表。

在 Python 中只有字符串有 in 运算符来检查一个字符串是否是另一个字符串的一部分。对于所有其他集合,您只能使用单个成员。引用 documentation ,

The operators in and not in test for collection membership. x in s evaluates to true if x is a member of the collection s, and false otherwise. x not in s returns the negation of x in s. The collection membership test has traditionally been bound to sequences; an object is a member of a collection if the collection is a sequence and contains an element equal to that object. However, it make sense for many other object types to support membership tests without being a sequence. In particular, dictionaries (for keys) and sets support membership testing.

For the list and tuple types, x in y is true if and only if there exists an index i such that x == y[i] is true.

For the Unicode and string types, x in y is true if and only if x is a substring of y. An equivalent test is y.find(x) != -1. Note, x and y need not be the same type; consequently, u'ab' in 'abc' will return True. Empty strings are always considered to be a substring of any other string, so "" in "abc" will return True.

关于python - 字符串与列表成员资格检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30175674/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com