查找列表b的子列表中的项目范围内的列表a中的项目 [英] Find if item in list a in range of items in sublist of list b

查看:51
本文介绍了查找列表b的子列表中的项目范围内的列表a中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有两个列表.

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

我想遍历x并确定它是否在y中其他项的范围内(在'_'上分割后).在这种情况下,由于不需要检查其他对象,因此它将退出循环.我不是要查看它属于多少范围,而只是出现一次.

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

推荐答案

如何检查数字是否在y列表中的任何数字范围之间.

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

注意: 否则,如果您使用的是Python 2,请始终使用xrange而不是range. xrange不会将所有数字保留在该范围内的内存中.当范围更大时,这将是一个问题. Python3将默认为xrange.

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.

这篇关于查找列表b的子列表中的项目范围内的列表a中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆