Getting list element's Attribute
I have two list. List1 contain objects and each object has node1 property. List2 contain lists of node which are the properties of objects stored in list1.
I want to create separate list which contain list of objects whose node present in list2. I want to create this list without using for loop because my object list is large so code takes long time to run if I use 开发者_Go百科for loop.
How can I achieve this in python?
Sounds like it's time to redesign your program. Replace list 2 with a defaultdict(None)
mapping the objects in list 1 to their node properties. Call it node
so you can get the node of an object x
with node[x]
. You can get the list of all nodes (unordered) with node.values()
in O(m) time where m is the number of objects that have an associated node.
(Alternatively, store a node
attribute in the objects with None
indicating no node and get the nodes with [x.node for x in list1 if x.node is not None]
; this takes O(n) time but may be faster than a for
loop.)
In my opinion there is no other way than by using a for
loop:
final_list = []
for obj in list1:
if obj.node1 in list2:
final_list.append(obj)
EDIT:
As for the comments, using a set
is faster for lookup elements (thanks eumiro):
set2 = set(list2)
...
if obj.node1 in set2:
Additionally you can write the code in one line (thanks rocksportrocker):
final_list = [obj for obj in list1 if obj not in set2]
精彩评论