How do I compare 2 lists and order 1 based on the number of matches
<p>Say you had a list, for example:</p>

<pre><code>first_list = ['a', 'b', 'c']
</code></pre>

<p>And you had the following list:</p>

<pre><code>second_list = ['a', 'a b c', 'abc zyx', 'ab cc ac']
</code></pre>

<p>How would you create a function that simply re-orders the second list based on the total number of times an element from the entire first list matches any part of an individual string from the second list?</p>

<hr>

<p><strong>For further clarity:</strong></p>

<ul>
<li>in the second list the 'a' string would contain 1 match</li>
<li>the 'a b c' string would contain 3 matches</li>
<li>the second example list would essentially end up in reverse order once the function has finished</li>
</ul>

<hr>

<p><strong>My attempt:</strong></p>

<pre><code>first_list = ['a', 'b', 'c']
second_list = ['a', 'a b c', 'abc zyx', 'ab cc ac']

print second_list

i = 0
for keyword in first_list:
    matches = 0
    for s in second_list:
        matches += s.count(keyword)
        if matches &gt; second_list[0].count(keyword):
            popped = second_list.pop(i)
            second_list.insert(0, popped)

print second_list
</code></pre>

<p>The most straightforward approach would be to use the <a href="https://docs.python.org/3.5/library/functions.html#sorted" rel="nofollow"><code>key</code> parameter of the <code>sorted</code> built-in function</a>:</p>

<pre><code>&gt;&gt;&gt; sorted(second_list, key = lambda s: sum(s.count(x) for x in first_list), reverse=True)
['ab cc ac', 'a b c', 'abc zyx', 'a']
</code></pre>

<p>The key function is called once per item in the list to be sorted. Still this is inefficient since <code>count</code> takes linear time.</p>

python