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 ite
Solution 1:
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 inzip(i.split("_"),i.split("_")[1:])]
l = {item:"Yes"ifany(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'}
Solution 2:
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)]>>defcheck_in_range(number):
found = 'no'for each_range iny_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.
Solution 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 inrange(j_1,j_2):
dict[i] = 'yes'breakelse:
dict[i] = 'no'
Returns output:
{2: 'yes', 12: 'no', 33: 'no', 40: 'yes', 500: 'no'}
Post a Comment for "Find If Item In List A In Range Of Items In Sublist Of List B"