Check if a Python list item contains a string inside another string
I have a list:
my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
and want to search for items that contain the string 'abc'
. How can I do that?
if 'abc' in my_list:
would check if 'abc'
exists in the list but it is a part of 'abc-123'
and 'abc-456'
, 'abc'
does not exist on its own. So how can I get all items that contain 'abc'
?
If you only want to check for the presence of abc
in any string in the list, you could try
some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
if any("abc" in s for s in some_list):
# whatever
If you really want to get all the items containing abc
, use
matching = [s for s in some_list if "abc" in s]
Use filter
to get at the elements that have abc
.
>>> lst = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
>>> print filter(lambda x: 'abc' in x, lst)
['abc-123', 'abc-456']
You can also use a list comprehension.
>>> [x for x in lst if 'abc' in x]
By the way, don't use the word list
as a variable name since it is already used for the list
type.
Just throwing this out there: if you happen to need to match against more than one string, for example abc
and def
, you can put combine two list comprehensions as follows:
matchers = ['abc','def']
matching = [s for s in my_list if any(xs in s for xs in matchers)]
Output:
['abc-123', 'def-456', 'abc-456']
链接地址: http://www.djcxy.com/p/55064.html
上一篇: 第十亿次相对进口