Check if a Python list item contains a string insi

2018-12-31 12:35发布

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' ?

标签: python
13条回答
墨雨无痕
2楼-- · 2018-12-31 13:00

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']
查看更多
长期被迫恋爱
3楼-- · 2018-12-31 13:01
x = 'aaa'
L = ['aaa-12', 'bbbaaa', 'cccaa']
res = [y for y in L if x in y]
查看更多
临风纵饮
4楼-- · 2018-12-31 13:08

Question : Give the informations of abc

    a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']


    aa = [ string for string in a if  "abc" in string]
    print(aa)

Output =>  ['abc-123', 'abc-456']
查看更多
唯独是你
5楼-- · 2018-12-31 13:12

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]
查看更多
残风、尘缘若梦
6楼-- · 2018-12-31 13:12

This is quite an old question, but I offer this answer because the previous answers do not cope with items in the list that are not strings (or some kind of iterable object). Such items would cause the entire list comprehension to fail with an exception.

To gracefully deal with such items in the list by skipping the non-iterable items, use the following:

[el for el in lst if isinstance(el, collections.Iterable) and (st in el)]

then, with such a list:

lst = [None, 'abc-123', 'def-456', 'ghi-789', 'abc-456', 123]
st = 'abc'

you will still get the matching items (['abc-123', 'abc-456'])

The test for iterable may not be the best. Got it from here: In Python, how do I determine if an object is iterable?

查看更多
有味是清欢
7楼-- · 2018-12-31 13:13
any('abc' in item for item in mylist)
查看更多
登录 后发表回答