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

谁都会走 提交于 2020-01-06 08:10:27

问题


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'}

回答1:


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.




回答2:


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'}



回答3:


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'}


来源:https://stackoverflow.com/questions/57487466/find-if-item-in-list-a-in-range-of-items-in-sublist-of-list-b

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!