Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient way to sort by number thresholds in Python?

Given a stream of dictionaries each with unique numerical ID, what would be the most efficient way to generate a list (or a format map-able into a sorted list) of IDs based on thresholds that do not increase linearly (<48, <103, <123...)? I've not looked extensively into itertools or other useful iteration libraries and I can't think of a much better way to group other than using elifs.

Example using if/elif/else:

dicts = [{'id':30},{'id':60},{'id':90},{'id':120},{'id':150}]
groups = [[] for _ in range(5)]

for a_dict in dicts:
    ID = a_dict['id']
    if ID < 50: groups[0].append(ID)
    elif ID < 100: groups[1].append(ID)
    elif ID < 150: groups[2].append(ID)
    elif ID < 200: groups[3].append(ID)
    else: groups[4].append(ID)

Output:

>>> print(groups)
[[30], [60, 90], [120], [150], []]
like image 307
wish Avatar asked Jan 24 '26 05:01

wish


1 Answers

The bisect algorithm should be the most efficient way to decide in which group an item belongs (assumes your groups are sorted). In fact the bottom of the page has an example similar to what you want to achieve.

>>> import bisect
>>> bins = [50, 100, 150, 200]
>>> bisect.bisect(bins, 30)
0
>>> bisect.bisect(bins, 60)
1
>>> bisect.bisect(bins, 220)
4

All in all

for a_dict in dicts:
    ID = a_dict['id']   # don't use Python built-in names
    index = bisect.bisect(bins, ID)
    groups[index].append(ID)
like image 162
Reti43 Avatar answered Jan 25 '26 19:01

Reti43



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!