Home > Net >  how to compare and count number of occurrences in two list of list?
how to compare and count number of occurrences in two list of list?

Time:03-18

I have two different list of list, with different size (List A with size in range 1000 and list B with size in range 10,000).

A=[[0, 0, 0],
 [0, 0, 1],
 [0, 0, 2],
 [0, 0, 3],
 [0, 0, 4],
 [0, 0, 5],
 [0, 1, 0],
 [0, 1, 1],
 [0, 1, 2],
 [0, 1, 3],
 [0, 1, 4],
 [0, 1, 5],
 [0, 1, 6],
 [0, 1, 7],
 [0, 1, 8],
 [0, 1, 9],
 [0, 2, 0],
 [0, 2, 1],
 [0, 2, 2]] 
B=[[1, 1, 2],
 [0, 0, 2],
 [0, 0, 1],
 [4, 2, 2],
 [3, 1, 2],
 [1, 0, 1],
 [1, 1, 2],
 [0, 1, 2],
 [0, 0, 0],
 [2, 2, 3],
 [1, 2, 1],
 [0, 2, 1],
 [0, 2, 0],
 [0, 2, 1],
 [0, 1, 3],
 [0, 0, 0],
 [1, 2, 5],
 [0, 4, 3],
 [0, 1, 3]]

I need to compare list with list B and find out how many times each element of A occur in B. For example I need to find out how many times [0,0,0] (first element of A) occur in B. Thank you for your help.

CodePudding user response:

This should work:

A = [[0, 0, 0],
 [0, 0, 1],
 [0, 0, 2],
 [0, 0, 3],
 [0, 0, 4],
 [0, 0, 5],
 [0, 1, 0],
 [0, 1, 1],
 [0, 1, 2],
 [0, 1, 3],
 [0, 1, 4],
 [0, 1, 5],
 [0, 1, 6],
 [0, 1, 7],
 [0, 1, 8],
 [0, 1, 9],
 [0, 2, 0],
 [0, 2, 1],
 [0, 2, 2]] 
B = [[1, 1, 2],
 [0, 0, 2],
 [0, 0, 1],
 [4, 2, 2],
 [3, 1, 2],
 [1, 0, 1],
 [1, 1, 2],
 [0, 1, 2],
 [0, 0, 0],
 [2, 2, 3],
 [1, 2, 1],
 [0, 2, 1],
 [0, 2, 0],
 [0, 2, 1],
 [0, 1, 3],
 [0, 0, 0],
 [1, 2, 5],
 [0, 4, 3],
 [0, 1, 3]]
nums = []
for i in A:
    for j in B:
        if i in B:
            nums.append(str(i))
nums_freq = {}
nums = list(dict.fromkeys(nums))
for i in nums:
    count = 0
    for j in B:
        if i == str(j):
            if i in nums_freq.keys():
                nums_freq[i]  = 1
            else:
                nums_freq[i] = 1

Value for num_freq:

{'[0, 0, 0]': 2,
 '[0, 0, 1]': 1,
 '[0, 0, 2]': 1,
 '[0, 1, 2]': 1,
 '[0, 1, 3]': 2,
 '[0, 2, 0]': 1,
 '[0, 2, 1]': 2}

CodePudding user response:

>>> import operator
>>> for e in A:
...     print(e, 'appearing in :',  operator.countOf(B, e))
...
[0, 0, 0] appearing in : 2
[0, 0, 1] appearing in : 1
[0, 0, 2] appearing in : 1
[0, 0, 3] appearing in : 0
[0, 0, 4] appearing in : 0
[0, 0, 5] appearing in : 0
[0, 1, 0] appearing in : 0
[0, 1, 1] appearing in : 0
[0, 1, 2] appearing in : 1
[0, 1, 3] appearing in : 2
[0, 1, 4] appearing in : 0
[0, 1, 5] appearing in : 0
[0, 1, 6] appearing in : 0
[0, 1, 7] appearing in : 0
[0, 1, 8] appearing in : 0
[0, 1, 9] appearing in : 0
[0, 2, 0] appearing in : 1
[0, 2, 1] appearing in : 2
[0, 2, 2] appearing in : 0
  • Related