Sunday, 15 August 2010

Merge two nested lists based on one attribute in Python -



Merge two nested lists based on one attribute in Python -

how merge 2 nested lists in python based on 1 attribute?

for example

list1 = [[1,false,true],[2,true,true],[3,true,false]] list2 = [[1,'mr.','child'],[2,'ms.','child'],[3,'mr.','adult']]

i want run like:

merged_list = merge(list1,list2, list1[0]==list2[0])

so final output be:

merged_list = [[1,false,true,'mr.','child'],[2,true,true,'ms.','child'],[3,true,false,'mr.','adult']]

i don't want utilize nested loop because of scalability; if trying merge 2 lists 1,000,000 rows take 1,000,000,000,000 iterations.

have thought going through dict way merge them?

def list_merge(list1, list2): d = {} x in list1 + list2: d.setdefault(x[0], []).extend(x[1:]) homecoming [[x] + y x, y in d.items()]

python list

No comments:

Post a Comment