0

I need to count how many times floating point value occurs in a list, and I have custom compare function (that compares floats with a relative tolerance).

Is there a simple solution to count element in a list using custom compare function?

As I understand, list.count() does not accept comparison function - only single argument to count.

user2052436
  • 4,321
  • 1
  • 25
  • 46
  • 1
    Please add input and output – Dani Mesejo Dec 05 '19 at 21:59
  • 3
    Please provide a [mcve] – Pitto Dec 05 '19 at 22:00
  • `sum(my_custom_compare(x, value_of_interest)==True for x in my_list)`? Also you should look at [What is the best way to compare floats for almost-equality in Python?](https://stackoverflow.com/questions/5595425/what-is-the-best-way-to-compare-floats-for-almost-equality-in-python) – pault Dec 05 '19 at 22:01
  • 3
    By the way, `== True` is superfluous. – kaya3 Dec 05 '19 at 22:15
  • I realize that. Just put it in to be explicit that I expected the compare function to return a bool. @kaya3 – pault Dec 06 '19 at 00:16

2 Answers2

0

I would try to convert custom compare function into custom convert function, which will take 1 float as an argument and output same result for every 2 matching floats. Then you can use e.g. itertools.groupby (the custom convert function would be round_func in my example):

a=[1.5, 3.2,5,9,4.2, 5.1, 4.1,1.57,0]
round_func=lambda x: round(x,0)
a=sorted(a, key=round_func)

import itertools

y=list(list(v) for k, v in itertools.groupby(a, key=round_func))
y=dict((el_in, len(el)) for el in y for el_in in el)

print(y)

Output:

{0: 1, 1.5: 2, 1.57: 2, 3.2: 1, 4.2: 2, 4.1: 2, 5: 2, 5.1: 2, 9: 1}
Grzegorz Skibinski
  • 12,624
  • 2
  • 11
  • 34
0

I assumed that your data is in a list named my_list and your custom compare function takes one parameter for comparison and returns boolean result. The result will be an integer showing number of elements which have your condition:

result = sum([1 for el in my_list if custom_compare(el)])

Tell me if any of my assumptions is wrong.

Hamidreza
  • 1,465
  • 12
  • 31