I would like to match sequential value pairs from 2 lists, a and b, and delete values from b list, keep only first larger value for b (compared to a) at same index position as a. lets look at a simple example
a = [206, 252, 272, 315, 349, 374, 394, 406, 440, 466]
b = [209, 220, 244, 255, 285, 301, 327, 358, 380, 396, 419, 447, 476, 492]
start by looking at value at index 0 in list a if b value at index 0 is smaller it shall be removed from b next look at index 1 in b , if smaller than a[0] it shall also be removed and so on...
final result should be :
b = [209,255,285,327,358,380,396,419,447,476]
my idea is to try a nested for loop
for idx, j in enumerate(a):
for jdx, k in enumerate(b):
if b[jdx] < a[idx]:
del b[jdx]
However, I can not get the final result I want...
CodePudding user response:
Your code is close, but it doesn't move to the next value in list a like you want. This code gives the intended result:
a = [206, 252, 272, 315, 349, 374, 394, 406, 440, 466]
b = [209, 220, 244, 255, 285, 301, 327, 358, 380, 396, 419, 447, 476, 492]
output = []
for idx, j in enumerate(a):
for jdx, k in enumerate(b):
if b[jdx] >= a[idx]:
output.append(b[jdx])
break
print(output)
Output:
[209, 255, 285, 327, 358, 380, 396, 419, 447, 476]
CodePudding user response:
I think this is an acceptable solution:
a = [206, 252, 272, 315, 349, 374, 394, 406, 440, 466]
b = [209, 220, 244, 255, 285, 301, 327, 358, 380, 396, 419, 447, 476, 492]
result = []
try:
a_iter = iter(a)
b_iter = iter(b)
a_value = next(a_iter)
b_value = next(b_iter)
while True:
if a_value < b_value:
result.append(b_value)
a_value = next(a_iter)
b_value = next(b_iter)
else:
b_value = next(b_iter)
except StopIteration:
print(result)
CodePudding user response:
Simple and efficient solution, go to the next index as soon as b[i] has become larger than a[i]:
i = 0
n = len(a)
for b[i] in b:
if i < n and b[i] > a[i]:
i = 1
del b[i:]
Or with a sentinel:
i = 0
a = b[-1:]
for b[i] in b:
if b[i] > a[i]:
i = 1
del b[i:]
