I'm using Python 3.5 and I'm wondering if there is a more efficient way to do this.
- I have two lists (
list1
andlist2
). - Each element in each list is a
set
of numbers. - In the example below,
list1
is basically a 1x4 "matrix" andlist2
is a 1x3 "matrix". - I want to make a 4x3 matrix that gives the length of the intersection of each element in
list1
with each element inlist2
Here is some sample code that works, but it's somewhat slow when the length of my lists is in the thousands.
Is there a faster/better way??
Thank you!
list1 = [{1,2,3}, {4,5,6}, {1,2,9}, {4,5,10}] # 1 x 4 "matrix"
list2 = [{1,3,9}, {4,2,8}, {1,0,10}] # 1 x 3 "matrix"
myoutputmatrix = []
for aset in list1:
small_list = [len(aset & asecondset) for asecondset in list2]
myoutputmatrix .append(small_list)
myoutputmatrix # [[2, 1, 1], [0, 1, 0], [2, 1, 1], [0, 1, 1]]