3

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], []]
wish
  • 33
  • 4

1 Answers1

5

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)
Reti43
  • 9,656
  • 3
  • 28
  • 44