简体   繁体   中英

Python list.count with custom compare

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.

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 eg 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}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM