In my Python application, I have the following lines:
for index, codec in enumerate(codecs):
for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']):
audio['hls']['group_id'].append(index)
How can I only trigger the append statement if the index hasn't been already appended previously ?
Thanks in advance
CodePudding user response:
Simply test if
your index not in
your list:
for index, codec in enumerate(codecs):
for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']):
if index not in audio['hls']['group_id']:
audio['hls']['group_id'].append(index)
CodePudding user response:
just add
for index, codec in enumerate(codecs):
for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']):
if index in audio['hls']['group_id']:
pass
else:
audio['hls']['group_id'].append(index)
CodePudding user response:
I think you're going about this backwards, very inefficiently. Right now, for each name, you loop through the entire job['audio']
sequence to find a match. This is O(n^2).
Instead, you could do a single pass over coedecs
to record the first occurrence of each one:
codec_map = {codec: len(codecs) - i - 1 for i, codec in enumerate(reversed(codecs))}
Reversing allows you to select the first index instead of the last, since the dictionary will contain the last key encountered. If you don't care whether it's first or last, you can simplify:
codec_map = {codec: i for i, codec in enumerate(codecs)}
Now the inner loop only needs to run once:
for audio in job['audio']:
if audio['hls']['codec_name'] in codec_map:
audio['hls']['group_id'].append(codec_map[audio['hls']['codec_name']])
This solution is O(N), and allows you to check things more efficiently.