我有清单:
myList = ['qwer', 'tyu', 'iop12', '3456789']
如何检查列表中的元素是否不包含搜索的子字符串,
- 对于字符串
'wer'
结果应为 False(包含子字符串的现有元素) - 对于字符串
'123'
结果应该是 True (没有元素包含这样的子字符串)
not any(search in s for s in myList)
或者:
all(search not in s for s in myList)
例如:
>>> myList = ['qwer', 'tyu', 'iop12', '3456789']
>>> not any('wer' in s for s in myList)
False
>>> not any('123' in s for s in myList)
True
你可以使用any
:
>>> myList = ['qwer', 'tyu', 'iop12', '3456789']
>>> not any('wer' in x for x in myList)
False
>>> not any('123' in x for x in myList)
True
内置any
和all
函数非常有用。
not any(substring in element for element in myList)
测试运行表明
>>> myList = ['qwer', 'tyu', 'iop12', '3456789']
>>> substring = 'wer'
>>> not any(substring in element for element in myList)
False
>>> substring = '123'
>>> not any(substring in element for element in myList)
True