简体   繁体   中英

Find if item in list a in range of items in sublist of list b

Let's say I have two lists.

x = [2,12,33,40,500]
y = ['1_4','9_11','38_50','300_400']

I would like to iterate through x and find determine if it is in the range of the other items in y (after splitting on '_'). If that is the case, it will break out of the loop since it does not need to check the others. I'm not trying to see how many ranges it falls into, only that it occurs once.

I think this code might work, but would like to double check.

x = [2,12,33,40,500]
y = ['1_4','9_11','38_50','300_400']

dict = {}

for i in x:
    for j in y:
        j_1 = int(j.split('_')[0])
        j_2 = int(j.split('_')[1])
        if i in range(j_1,j_2):
            dict[i] = 'yes'
            break
        else:
            dict[i] = 'no'
            #the else statement is what's tricking me

The solution should yield the following in this example:

dictt = {2:'yes',12:'no',33:'no',40:'yes',500:'no'}

Since you are testing a case versus any of the combinations within the list y , why not use any ?

x = [2,12,33,40,500]
y = ['1_4','9_11','38_50','300_400']

y_new = [(int(a),int(b)) for i in y for a,b in zip(i.split("_"),i.split("_")[1:])]

l = {item:"Yes" if any(a<item<b for a,b in y_new) else "No" for item in x}

print (l)

#{2: 'Yes', 12: 'No', 33: 'No', 40: 'Yes', 500: 'No'}

How about checking if the number is in between any of the range of numbers in the y list.

>> x = [2,12,33,40,500]
>> y = ['1_4','9_11','38_50','300_400']
>> y_new = map(lambda x: tuple(map(int, x.split('_'))), y)
# y_new = [(1, 4), (9, 11), (38, 50), (300, 400)]
>> def check_in_range(number):
        found = 'no'
        for each_range in y_new:
             if each_range[0] <= number <= each_range[1]:
                 found = 'yes'
        return found
>> dict(zip(x, map(check_in_range, x)))
>> {2: 'yes', 12: 'no', 33: 'no', 40: 'yes', 500: 'no'}

Note: Otherwise, if you are using Python 2, always use xrange and not range . xrange will not keep all the numbers in the memory which range does. This will be an issue when the range is bigger. Python3 will default to xrange.

It does work. As you wrote it.

x = [2,12,33,40,500]
y = ['1_4','9_11','38_50','300_400']
dict = {}

for i in x:
    for j in y:
        j_1 = int(j.split('_')[0])
        j_2 = int(j.split('_')[1])
        if i in range(j_1,j_2):
            dict[i] = 'yes'
            break
        else:
            dict[i] = 'no'

Returns output:

{2: 'yes', 12: 'no', 33: 'no', 40: 'yes', 500: 'no'}

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