I have two lists, A and B. I want to generate a third list that is 1 if the corresponding entry in A has an entry in the list B at the end of the string and 0 otherwise.
A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May']
B = ['Smith', 'Stirling', 'Doe']
[0, 1, 0, 0, 0]
A = [' Tom Barry Stirling Adam', 'Maddox Smith', 'George Washington Howard Smith']
B = ['Washington Howard Smith', 'Stirling Adam']
[1, 0, 1]
[1 if y.endswith(x) else 0 for x in B for y in A]
A much faster way is to pass a tuple to endswith:
In : A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May'] In : B = ['Smith', 'Stirling', 'Doe'] In : A *= 1000 In : %%timeit t = tuple(B) [int(s.endswith(t)) for s in A] ....: 100 loops, best of 3: 5.02 ms per loop In : timeit [int(any(full.endswith(last) for last in B)) for full in A] 100 loops, best of 3: 21.3 ms per loop
You make one function call per element in
A as opposed to one function call for potentially every element in B for each in
A and without the overhead of the generator used with any.