Check if a Python list item contains a string inside another string

前端 未结 18 1843
-上瘾入骨i
-上瘾入骨i 2020-11-22 02:18

I have a list:

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

and want to search for items that contain the string \'

相关标签:
18条回答
  • 2020-11-22 03:10
    for item in my_list:
        if item.find("abc") != -1:
            print item
    
    0 讨论(0)
  • 2020-11-22 03:13

    If you want to get list of data for multiple substrings

    you can change it this way

    some_list = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
    # select element where "abc" or "ghi" is included
    find_1 = "abc"
    find_2 = "ghi"
    result = [element for element in some_list if find_1 in element or find_2 in element] 
    # Output ['abc-123', 'ghi-789', 'abc-456']
    
    0 讨论(0)
  • 2020-11-22 03: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.

    0 讨论(0)
  • 2020-11-22 03:15

    If you just need to know if 'abc' is in one of the items, this is the shortest way:

    if 'abc' in str(my_list):
    
    0 讨论(0)
  • 2020-11-22 03:15
    any('abc' in item for item in mylist)
    
    0 讨论(0)
  • 2020-11-22 03:19

    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.

    0 讨论(0)
提交回复
热议问题