user18726875
user18726875

Reputation:

append only if item isn't already appended?

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?

Upvotes: 5

Views: 88

Answers (4)

Haoliang
Haoliang

Reputation: 1264

Using in operator in list works, but it is less efficient than in operator in set. You can use the set data structure to improve the efficiency:

visited_indices = set()
for index, codec in enumerate(codecs):
    for audio in filter(lambda x: x['hls']['codec_name'] == codec, job['audio']):
        if index not in visited_indices:
            audio['hls']['group_id'].append(index)
            visited_indices.add(index)

Upvotes: 0

Mad Physicist
Mad Physicist

Reputation: 114440

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.

Upvotes: 4

Ananta R. Pant
Ananta R. Pant

Reputation: 106

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)

Upvotes: 1

Synthaze
Synthaze

Reputation: 6090

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)

Upvotes: 3

Related Questions