简体   繁体   English

Python中if not条件下如何获取下一个满足条件的i?

[英]How to get the next i that meets the condition under the if not condition in Python?

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 .我想写这样的代码,但问题是我不知道如何表达满足条件的下一个 i Simply use i+1 is definitely wrong.简单地使用 i+1 肯定是错误的。 Can somebody help me?有人可以帮助我吗? Thank you very much, guys!!非常感谢你们!!

Adjusting the range for your loop makes it easier to access the current and next element of b :调整循环的范围可以更轻松地访问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]

You didn't mention about additional restrictions so there are no checking if our lists are empty or contain just 1 element.你没有提到额外的限制,所以没有检查我们的列表是空的还是只包含 1 个元素。

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":如果您不想使用“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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM