is it possible to sort through a list and do something depending on your preferred order or pre determined choice?
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
i started to explore the below idea but i cannot seem to get it to print only the highest -currently it prints all 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
any help would be awesome
答案 0 :(得分:2)
由于您的definitions
正常,您可以遍历列表,并在找到匹配项时返回文件。
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
答案 1 :(得分:1)
如果您只想要一个结果(最高)并且考虑到您的列表从最高到最低排序,您可以在找到第一个结果后返回:
import re
definitions = ['1080p', '720p', 'SD'] # order (highest to lowest)
some_files = ['movie_a_1080p.mp4', 'movie_b_720p.mp4', 'movie_c_SD.mp4']
def find():
for each in some_files:
for defs in definitions:
match = re.search(defs, each, re.M | re.I)
if match:
return match.group(0)
print(find())
答案 2 :(得分:1)
如果我理解你要做什么,这应该有效:
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
您的方法的主要问题是break
仅突破最近的循环。 @ alfasin的答案通过函数return
来修复此问题。
如果你愿意,我的答案也可以在没有函数的情况下使用,因为它只有一个循环可以突破:
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