背景:
示例列表:mylist = ['abc123', 'def456', 'ghi789']
如果子字符串匹配,我想检索一个元素,例如abc
代码:
sub = 'abc'
print any(sub in mystring for mystring in mylist)
上面打印True
列表中的任何元素是否包含该模式。
我想打印与子字符串匹配的元素。因此,如果我正在检查'abc'
,我只想'abc123'
从列表中打印。
print [s for s in list if sub in s]
如果您希望它们用换行符分隔:
print "\n".join(s for s in list if sub in s)
完整示例,不区分大小写:
mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'
print "\n".join(s for s in mylist if sub.lower() in s.lower())
所有答案都有效,但它们总是遍历整个列表。如果我理解你的问题,你只需要第一场比赛。因此,如果您找到了第一个匹配项,则不必考虑列表的其余部分:
mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'
如果匹配位于列表的末尾或非常小的列表,则没有什么区别,但请考虑以下示例:
import timeit
mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'
timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000)
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4
使用一个简单的for
循环:
seq = ['abc123', 'def456', 'ghi789']
sub = 'abc'
for text in seq:
if sub in text:
print(text)
产量
abc123
我只是使用一个简单的正则表达式,你可以做这样的事情
import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
print item
这将打印所有包含 sub 的元素:
for s in filter (lambda x: sub in x, list): print (s)