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

前端 未结 18 1885
-上瘾入骨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: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.

提交回复
热议问题