sort a list by prefered order
<p>is it possible to sort through a list and do something depending on your preferred order or pre determined choice?</p>

<p>so i have a list of files containing definitions, if i re.search the string and return a match, i would like to only print the string + highest definition</p>

<p>i started to explore the below idea but i cannot seem to get it to print only the highest -currently it prints all 3</p>

<pre><code>#!/usr/bin/python3
import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4','movie_c_SD.mp4'] 

for each in some_files:
    for defs in definitions:
        match = re.search(defs, each, re.M | re.I)
        if match:
            if match.group() == '1080p':
                print('1080p', each)
                break
            else:
                if match.group() == '720p':
                    print('720p', each)
                    break
                else:
                if match.group() == 'SD':
                    print('SD', each)
                    break
</code></pre>

<p>any help would be awesome</p>

<p>If I understand what you're trying to do, this should work:</p>

<pre><code>def best(some_files):
    for definition in ('1080p', '720p', 'SD'):
        match = next((file for file in some_files if definition in file), None)
        if match is not None:
            return match

print(best(['movie_a_1080p.mp4', 'movie_b_720p.mp4', 'movie_c_SD.mp4']))  # movie_a_1080p.mp4
print(best(['movie_b_720p.mp4', 'movie_c_SD.mp4', 'movie_a_1080p.mp4']))  # movie_a_1080p.mp4
print(best(['movie_b_720p.mp4', 'movie_c_SD.mp4']))  # movie_b_720p.mp4
print(best(['movie_d.mp4', 'movie_c_SD.mp4']))  # movie_c_SD.mp4
print(best(['movie_d.mp4']))  # None
</code></pre>

<p>The main issue with your approach is that the <code>break</code> only breaks out of the nearest loop. @alfasin's answer fixes this by <code>return</code>ing from a function instead.</p>

<p>My answer could also just be used without a function if you want, since it only has one loop to break out of:</p>

<pre><code>for definition in ('1080p', '720p', 'SD'):
    match = next((file for file in some_files if definition in file), None)
    if match is not None:
        print('Found the best one: {}'.format(match))
        break
</code></pre>

python python-2.7 python-3.x