Home > Software engineering >  How to get the next i that meets the condition under the if not condition in Python?
How to get the next i that meets the condition under the if not condition in Python?

Time:12-12

My problem is a bit difficult to describe, I want to use an example to show my problem.

For example, each number corresponds to a corresponding value,

a=[0,3,5]
b=[0,1,2,3,4,5,6,7]
for i in range(b):
  if i not in a:
    if ***value of i < value of next i that meet the condition***
      a.append(i)
    else:
      a.append(***next i that meet the condition***)

I want to write code like this but the problem is that I don't know how to express the next i that meet the condition. Simply use i 1 is definitely wrong. Can somebody help me? Thank you very much, guys!!

CodePudding user response:

Adjusting the range for your loop makes it easier to access the current and next element of b:

a = [0, 3, 5]
b = [0, 1, 12, 2, 16, 3, 18, 4, 20, 5, 22]

for index in range(1, len(b) - 1):
    current_item = b[index - 1]
    next_item = b[index]

    if current_item in a:
        continue

    if current_item < next_item:
        a.append(current_item)
    else:
        continue

print(a)

Out:

[0, 3, 5, 1, 2, 4]

CodePudding user response:

You didn't mention about additional restrictions so there are no checking if our lists are empty or contain just 1 element.

You can consider using this:

a = [0, 3, 5]
b = [0, 1, 2, 3, 4, 5, 6, 7]

for i in range(len(b) - 1):
    if (b[i] < b[i   1]) and b[i] not in a:
        a.append(b[i])

print(a)

And this is another version if you don't want to use "i 1":

a = [0, 3, 5]
b = [0, 1, 2, 3, 4, 5, 6, 7]
for n, m in zip(b[:-2], b[1:]):
    if n < m and n not in a:
        a.append(n)

print(a)
  • Related