python - 按首选顺序对列表进行排序

标签 python python-2.7 python-3.x

是否可以对列表进行排序并根据您的首选顺序或预先确定的选择执行某些操作?

所以我有一个包含定义的文件列表,如果我重新搜索字符串并返回匹配项,我只想打印字符串+最高定义

我开始探索下面的想法,但我似乎无法让它只打印最高的 - 目前它打印所有 3

#!/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

任何帮助都会很棒

最佳答案

由于您的定义是有序的,您只需遍历列表,并在找到匹配项时返回文件。

def best_quality(l):
    definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
    for definition in definitions:
        for file in some_files:
            if definition in file: return file

some_files = ['movie_c_SD.mp4', 'movie_a_1080p.mp4', 'movie_b_720p.mp4']
print best_quality(some_files)
>>> movie_a_1080p.mp4       

关于python - 按首选顺序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39257017/

相关文章:

python - f2py 在 Fortran 中的 Python 回调函数中使用数组

python - Django Elastic Beanstalk 部署显示 404

python - 我如何构建动态查询elasticsearch dsl python

python-3.x - 使用 Pandas DataFrame 的 groupby 方法时出现 StopIteration 错误

python - 什么是 <class 'range' >

python - For循环在Beautiful Soup中迭代div

python - 字符串索引必须是整数而不是 str 字典

csv - 使用Python的csv.dictreader搜索特定键然后打印其值

python - 无法在正则表达式中使用变量

python - 将两个 df 和 tag 与列名匹配