简体   繁体   English

从python中的最小迭代中获取另一个列表中的列表

[英]get a list from another list with minimum iteration in python

I have a list (Let A) which contains list of object and each object contains attribute say name and id and id values are stored in database.In a particular position I have list (Let B) of IDs now i want those objects in list 'A' which have ids in list 'B'. 我有一个列表(Let A),其中包含对象列表,每个对象包含属性,例如nameidid值存储在database.In特定位置我有ID列表(Let B)现在我想要列表中的那些对象'A'在列表'B'中有id。
by using simple iteration i can get those objects from list A.(It may cause more iteration) I want to reduce the iteration as my both lists have more than 1000 of values in each 通过使用简单的迭代我可以从列表A中获取这些对象。(它可能会导致更多的迭代)我想减少迭代,因为我的两个列表每个都有超过1000个值

for clildB in B:
            for childA in A:
                #   MYCODE

To convert your O(n*m) (quadratic) code to O(n+m) (linear): 要将O(n * m)(二次)代码转换为O(n + m)(线性):

ids = set(B)
L = [obj for obj in A if obj.id in ids]

item in a_set operation has O(1) (constant) time complexity (average case) , where a_set is a set. item in a_set操作中的item in a_set具有O(1)(常量)时间复杂度(平均大小写) ,其中a_set是一个集合。 Compare it with item in a_list that has O(n) time complexity, where a_list is a list. 将它与item in a_list中具有O(n)时间复杂度的item in a_list比较,其中a_list是一个列表。

idADic = {o['id']:o for o in A}
[idADic.get(o['id']) for o in B]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM