Skip to content Skip to sidebar Skip to footer

Apply Multiple Ranges To One List

I am trying to loop through a long list of data which needs to be sorted by range, and then I need to count the integers in each range. The following code works if you continually

Solution 1:

Maintain an upper bound, iterate in sorted list, when number exceeds bound increase bound by 100

import random
lisst = [209, 166, 38, 1090, 1091, 1092, 1099, 2011]
cnts = []
cnt = 0
up = 100for num insorted(lisst):
    if num <= up:
        cnt+=1else:
        while num > up:
            cnts.append(cnt)
            cnt=0
            up+=100
        cnt=1
cnts.append(cnt)
for i inrange(len(cnts)):
    print(str(i*100+1) + "-" + str(i*100+100) + " = " + str(cnts[i]))

Solution 2:

You can use integer division to break the numbers into ranges, and then use the values from the integer division to put the values into a list, so:

from collections importdefaultdictnums= [10, 50, 210, 300, ...]
bin_sort = defaultdict([])

for num in nums:
    bin_sort[num//100].append(num)

bin_sort will contain all the values that you need organized into what range increment you are on. So to get the 0-100 bin you would print:

>>>print(bin_sort[1])
[10, 50, ...]

It's also worth looking at bucket sorts for this sort of thing (Algorithms for bucket sort)

Solution 3:

This should work for you and doesn't require external libraries like collections

ranges = { # (start, end): [count, [number list]]
(0, 101): [0, []],
(101, 201): [0, []],
(201, 301): [0, []]
}

with open('numbers.txt', 'r') as f:
    for line in f.readlines():
        numbers = [int(n) for n in line.split()]
        for num in numbers:
            for start, endin ranges.keys():
                if start <= num < end:
                    ranges[(start, end)][0] += 1
                    ranges[(start, end)][1].append(num)

for range_ in ranges.keys():
    print("{}-{}: {}".format(range_[0], range_[1], ranges[range_][0]))

Solution 4:

Another possible iterative solution:

import math

withopen('numbers.txt', 'r') as f:
    numbers = [int(x) for x in f.readlines()]
    ranges = math.ceil(max(numbers) / 100)

    for r inrange(ranges):
        bottom = r * 100
        top = bottom + 101
        range_count = [num for num in numbers if num inrange(bottom, top)]
        print('Number in Range {}: {}'.format(r, len(range_count)))

Post a Comment for "Apply Multiple Ranges To One List"