user3792245
user3792245

Reputation: 828

Looping through a 2-D list within a 1-D list

I have 2 lists:

I am trying to gather a count of how many times each element in x_int_loc lies within the range of values in the xtremes list. That is, count of 1 (in list x_int_loc) will be 2, as it appears in [0,2], [0,3] and so on.

Although this appears to be quite simple, I got a bit stuck while looping through these lists. Here is my code:

for i in range(len(x_int_loc)):
    while k < len(xtremes):
        if x_int_loc[i]>xtremes[k][0] and xtremes[k][1] > x_int_loc[i]:
            count[i] = count[i]+1
print(count[:])

Could any of you please tell me where I am going wrong?

Upvotes: 0

Views: 55

Answers (2)

Abhijit
Abhijit

Reputation: 63717

Unless you are too particular about optimization, in general cases, the following solution would be optimal

>>> x_int_loc = [0,1,2,3,4,5]
>>> xtremes = [[0,2],[0,3],[1,3],[1,5],[2,5],[3,6],[4,8]]
>>> xtremes_ranges = [xrange(r[0]+1,r[1]) for r in xtremes]
>>> [(x, sum(x in r for r in xtremes_ranges)) for x in x_int_loc]
[(0, 0), (1, 2), (2, 3), (3, 2), (4, 3), (5, 2)]

Upvotes: 1

jonrsharpe
jonrsharpe

Reputation: 121986

You never increment k, or reset it when i increments. The minimal fix is:

for i in range(len(x_int_loc)):
    k = 0
    while k < len(xtremes):
        if x_int_loc[i]>xtremes[k][0] and xtremes[k][1] > x_int_loc[i]:
            count[i] = count[i]+1
        k += 1

It is not good practice to use a while loop with a manual index; as this clearly demonstrates, it is error prone. Why not just for loop over xtremes directly? All you really need is:

count = [sum(x < n < y for x, y in xtremes) for n in x_int_loc]

which gives me:

>>> count
[0, 2, 3, 2, 3, 2]

Upvotes: 2

Related Questions