仅当项目IS IS IS IS已附加时附加?
在我的Python应用程序中,我有以下几行:
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)
如果以前尚未附加索引,我如何仅触发附加
语句?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
我认为您会倒退,非常效率。现在,对于每个名称,您可以循环浏览整个
作业['audio']
序列以查找匹配项。这是O(n^2)。取而代之的是,您可以通过
coedecs
进行一次通行证以记录每个事件的第一次出现:反向允许您选择第一个索引而不是最后一个索引,因为字典将包含遇到的最后一个键。如果您不在乎它是第一个还是最后一个,则可以简化:
现在,内部循环只需要运行一次:
此解决方案是O(n),并允许您更有效地检查事物。
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: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:
Now the inner loop only needs to run once:
This solution is O(N), and allows you to check things more efficiently.
只需测试如果您的索引
不在
您的列表中:Simply test
if
your indexnot in
your list:只是添加
just add
在中使用
在
运算符,但在list
工作中使用set set
中的操作符中的效率不如。您可以使用设定的数据结构来提高效率:
Using
in
operator inlist
works, but it is less efficient thanin
operator inset
. You can use the set data structure to improve the efficiency: