I am trying to figure out how to compare n
lists to find the different items.
For example, consider the list:
list_l = [[1,2,3,4,5,100],
[1,2,31,41,51],
[10,2,3,45,25],
[4,20,3,4,12,51,200]
]
Each item is unique for each list in list_l
. e.g. the list [1,2,3,4,5,100]
has no duplicate elements. The same goes for the list [1,2,31,41,51]
, etc...
find_differences(list_l)
Expected outputs
res = [[5, 100], [31, 41], [10, 45, 25], [20, 12, 200]]
[5, 100] # elements of this list appears only in list [1,2,3,4,5,100]
[31, 41] # elements of this list appears only in list [1,2,31,41,51]
[10, 45, 25] # same here
[20, 12, 200] # same here
This example only has 4 lists and few items. However, my use case has many more lists and each list contains hundreds of items.
Using the set
function gives a list
of differences between the input lists. The resulting list, however, does not make it possible to distinguish which item originally belongs to which list.
Any help would be highly appreciated!
CodePudding user response:
Python has sets which have an intersection and a difference property.
s1 = set([1,2,3,4,5,100])
s2 = set([1,2,31,41,51])
s1.difference(s2)
Using this you can do what you're attempting!
I am a little worried this is a homework problem, so I don't think it makes sense to fully elaborate here.
CodePudding user response:
Here is a solution to my problem.
results = []
for init_list in list_l:
temp = []
for e in init_list:
unique_item = True
for each_list in list_l:
# Check if e is not unique, and if init_list and each_list are not the same list
if e in each_list and init_list != each_list:
unique_item = False
break
# concatenate all unique items of a list
if unique_item:
temp.append(e)
results.append(temp)