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:15

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.

查看更多
只若初见
3楼-- · 2018-12-31 13:17

From my knowledge, a 'for' statement will always consume time.

When the list length is growing up, the execution time will also grow.

I think that, searching a substring in a string with 'is' statement is a bit faster.

In [1]: t = ["abc_%s" % number for number in range(10000)]

In [2]: %timeit any("9999" in string for string in t)
1000 loops, best of 3: 420 µs per loop

In [3]: %timeit "9999" in ",".join(t)
10000 loops, best of 3: 103 µs per loop

But, I agree that the any statement is more readable.

查看更多
浪荡孟婆
4楼-- · 2018-12-31 13:20

This is the shortest way:

if 'abc' in str(my_list):
查看更多
情到深处是孤独
5楼-- · 2018-12-31 13:22
for item in my_list:
    if item.find("abc") != -1:
        print item
查看更多
旧人旧事旧时光
6楼-- · 2018-12-31 13:23

I'm new to python. Got below code working and easy to understand

my_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    for str in my_list:
        if 'abc' in str:
            print(str)
查看更多
君临天下
7楼-- · 2018-12-31 13:23
mylist=['abc','def','ghi','abc']

pattern=re.compile(r'abc') 

pattern.findall(mylist)
查看更多
登录 后发表回答