-1

I have a target list as

target_list = ['one', 'two', 'three','four', 'five']

And a output list as

output_list = ['two','three','four', 'five']

The target_list is fixed, while the output_list will change depending on the output of some function. I want to find which element will be missed in the target_list based on the observation from output_list.

As in the above example, the element one is missing. I also want to count the number of missing element. Could you help me to do it in python?

Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
Jame
  • 3,746
  • 6
  • 52
  • 101

3 Answers3

5

You are going to have to compare if each item of a list is contained in the other one; probably the most efficient iway to do this is to use sets() and extract their difference.

target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']

print(set(target_list).difference(set(output_list)))

output:

set(['one'])
Reblochon Masque
  • 35,405
  • 10
  • 55
  • 80
3

You can find the missing elements by using Counter. Every missing element has its occurrence.

from collections import Counter
target_list = ["one", "two", "three", "four", "five"]
output_list = ['two','three','four', 'five']
Counter(target_list)-Counter(output_list)

Output:

Counter({'one': 1})
chx3
  • 238
  • 5
  • 10
1
target_list=['one', 'two', 'three','four', 'five']
output_list=['two','three','four', 'five']

l = [x for x in target_list if x not in output_list]
print("Number of items missing: " + len(l))

for x in target_list:
    if x in l:
        print(x + " is missing")
    else:
        print(x + " is not missing")

Output

one is missing
two is not missing
three is not missing
four is not missing
five is not missing
Van Peer
  • 2,127
  • 2
  • 25
  • 35
  • Thanks. How to count the `one` is missing 1. The len only count the number of missing, not the number of missing in each element – Jame Nov 13 '17 at 07:52
  • @Jame you want output as `one is missing`? – Van Peer Nov 13 '17 at 07:54
  • Yes. The output is right. One requirement counts the number of missing in each element. For example, the one is 1 missing, two is zero.... – Jame Nov 13 '17 at 07:55