0

I am struggling with getting the output that I want. I have two lists as illustrated below:

h3_FP_DB = [['KE', 'EH', 'LA'], ['KE', 'EH'], ['KE'], ['EH'], ['KE', 'EH']]

h3_FP = [['KE'], ['KE', 'LA'], ['KE', 'EH', 'LA'],  ['KE', 'EH'], ['LA'], ['LA', 'EH'], ['EH']]

I would like to know the occurrence for every nested lists in h3_FP in the list h3_FP_DB. So using the example above my desired output would give the counts below. I don not know which type/structure is beneficial:

KE: 4
KE, LA: 1
KE, EH, LA: 1
KE, EH: 3
LA: 4
LA, EH: 1
EH: 4

Using the code in this example I made the following code:

h3_FP_Occurence = []

for i in range(len(h3_FP)):
  count = len([i for idx in range(len(h3_DB_FP)) if h3_DB_FP[idx : idx + len(i)] == i])
  h3_DB_FP.append(count)

This gives me the following error

TypeError: object of type 'int' has no len()

I have looked extensively in Stack overflow and the web but I couldn't find anything. Any idea on how I can count the occurrences of the nested lists in the main list?

MxGr20
  • 77
  • 6

1 Answers1

2

You can use a nested dictionary/list comprehension to check whether each value in each list in h3_FP is in each list in h3_FP_DB, outputting the results into a list of dictionaries:

h3_FP_Occurence = [{ ', '.join(l): sum(all(v in hl for v in l) for hl in h3_FP_DB) } for l in h3_FP]

Output:

[
 {'KE': 4},
 {'KE, LA': 1},
 {'KE, EH, LA': 1},
 {'KE, EH': 3},
 {'LA': 1},
 {'LA, EH': 1},
 {'EH': 4}
]
Nick
  • 138,499
  • 22
  • 57
  • 95