【问题标题】:How to get the next i that meets the condition under the if not condition in Python?Python中if not条件下如何得到满足条件的下一个i?
【发布时间】:2022-01-15 19:05:34
【问题描述】:

我的问题有点难以描述,我想用一个例子来说明我的问题。

例如每个数字对应一个对应的值,

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。简单地使用 i+1 肯定是错误的。有人可以帮助我吗?非常感谢你们!!

【问题讨论】:

  • 你能指出你想在每一步附加到a的值吗?

标签: python list python-2.7 loops


【解决方案1】:

调整循环的范围可以更轻松地访问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)

输出:

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

【讨论】:

    【解决方案2】:

    你没有提到额外的限制,所以没有检查我们的列表是空的还是只包含 1 个元素。

    你可以考虑使用这个:

    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)
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-19
      • 2015-10-27
      • 1970-01-01
      • 1970-01-01
      • 2021-05-25
      • 2020-03-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多