Using a list comprehension to label data that is common to two lists
<p>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.</p>

<pre><code>A = ['Mary Sue', 'John Doe', 'Alice Stella', 'James May', 'Susie May']
B = ['Smith', 'Stirling', 'Doe']
</code></pre>

<p>I want a list comprehension that will give the result</p>

<pre><code>[0, 1, 0, 0, 0]
</code></pre>

<p>Keep in mind that this is a specific case of a more general problem.  Elements in A can have arbitrary white space and contain an arbitrary number of words in them.  Likewise elements in B can have an arbitrary number of words.  For example</p>

<pre><code>A = ['  Tom Barry Stirling Adam', 'Maddox Smith', 'George Washington Howard Smith']
B = ['Washington Howard Smith', 'Stirling Adam']
</code></pre>

<p>should return</p>

<pre><code>[1, 0, 1]
</code></pre>

<p>So far I have the following</p>

<pre><code>[1 if y.endswith(x) else 0 for x in B for y in A]
</code></pre>

<p>However the length of the returned list is not the dimension that I want because it gives a 0 or 1 for every combination of A[i], B[j] elements.  I am not interested in solutions using for loops, I need a list comprehension for speed.</p>

<pre><code>&gt;&gt;&gt; [[0, 1][name.split()[-1] in set(B)] for name in A]
[0, 1, 0, 0, 0]
</code></pre>

<p>edit: For finer control over the check.</p>

<p><a href="https://docs.python.org/2/library/stdtypes.html#str.split" rel="nofollow"><strong><code>str.split</code></strong></a> can take a parameter which is the maximum splits to make. e.g:</p>

<pre><code>&gt;&gt;&gt; 'Mary Pat Sue'.split(maxsplit=1)
['Mary', 'Pat Sue']
</code></pre>

<p>Then we could compare to see if any name in <code>B</code> is in the second value of split:</p>

<pre><code>&gt;&gt;&gt; B = ['Pat', 'Sue']
&gt;&gt;&gt; any(name in 'Pat Sue' for name in B)
True
</code></pre>

<p>So altogether:</p>

<pre><code>&gt;&gt;&gt; [[0, 1][any(surname in fullname.split(maxsplit=1)[-1] for surname in B)]
     for fullname in A]
</code></pre>

python python-3.x list-comprehension