现在,我有类似的东西:
media_info = MediaInfo.parse(file_path).to_data()
local_file_info = [ media_info['tracks'][1]['frame_rate'],
media_info['tracks'][1]['other_display_aspect_ratio'],
media_info['tracks'][2]['other_sampling_rate'],
media_info['tracks'][2]['other_channel_s'],
media_info['tracks'][3]['Format']]
当元素不存在时,我该如何愚蠢地将其赋值为None而不是抛出IndexError? (例如:用MediaInfo解析的文件在视频文件中没有字幕轨道,因此没有第三轨道)
我知道我可以用肮脏的方式做到这一点:
try:
local_file_info.append(media_info['tracks'][1]['frame_rate'])
except IndexError
local_file_info.append(None)
try:
local_file_info.append(media_info['tracks'][1]['other_display_aspect_ratio'])
except IndexError
local_file_info.append(None)
try:
local_file_info.append(media_info['tracks'][2]['other_sampling_rate'])
except IndexError
local_file_info.append(None)
try:
local_file_info.append(media_info['tracks'][2]['other_channel_s'])
except IndexError
local_file_info.append(None)
try:
local_file_info.append(media_info['tracks'][3]['Format'])
except IndexError
local_file_info.append(None)
但这看起来太可怕了,我敢肯定有更好的方法来做到这一点。
答案 0 :(得分:2)
您的代码的明显问题是大量的代码重复。减少代码重复的两个有用工具是
media_info
5次,不如编写一个为您执行此操作的循环。try...except
块复制/粘贴5次,不如将其包装在函数中。理想情况下,您应该同时进行以下操作:
media_keys = [
(1, 'frame_rate'),
(1, 'other_display_aspect_ratio'),
(2, 'other_samping_rate'),
(2, 'other_channel_s'),
(3, 'Format')
]
def get_media_info(index, key):
try:
return media_info['tracks'][index][key]
except IndexError:
return None
local_file_info = [get_media_info(*keys) for keys in media_keys]
答案 1 :(得分:-2)
如果条件允许,将使用快速修复方法
play
但是它仍然不能解决您的问题,因为它看起来仍然很恐怖,但至少不是肮脏的方式