Python如何在下一次迭代中使用几次相同的代码?

2024-06-25 23:28:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我想搜索一个列表:

[0, 0, 1, 0, 1, 1, 1, 0, 1, 1] 

以及替换/编辑与上一项和下一项不同的项。对于xxsample:我想去掉上面列表中索引2处的/edit1。你知道吗

看看下面的代码,请继续阅读代码下面的核心问题:

!更新:结果应为:[0,0,0,0,1,1,1,1,1,1]

x = [0, 0, 1, 0, 1, 1, 1, 0, 1, 1]
print(x)
hiter = iter(x)
next(hiter)
prev = None

for i in x:
    try:
        print('prev %s - CURRENT %s - next %s' % (prev, i, next(hiter)))
        prev = i

        #if i != prev and i != next(hiter):
        #   x[i] = prev 

    except StopIteration:
        break

print(x)

我们知道上一项、下一项和当前项。你知道吗

但每次我使用:

if i != prev and i != next(hiter)...

next(hiter)破坏秩序。换句话说,如果我在循环中使用next(hiter)超过一次,Python会将下一项读取为double,因为我在循环中使用了next(hiter两次。你知道吗

我还试图声明像y = next(hiter)这样的独立变量,但仍然没有起作用(显然不起作用,但无论如何我都非常想检查它)。你知道吗

我没有任何线索,另外,hiter.__next__()next(hiter)做的一样。你知道吗


Tags: and代码none编辑核心列表forif
3条回答

您可以使用一个生成器来保留上一个项目并向前看一个项目:

def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    # create a list containing the previous element, the current element and the next element
    # and iterate over your input.
    three = [None, first, next(x)]
    for item in x:
        # Update the list of elements: Remove the previous previous item and
        # add the new next item.
        three = three[1:] + [item]
        prev, cur, nxt = three

        if cur != prev and cur != nxt:
            three[1] = prev  # replace the current item with the previous item
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield three[-1]


>>> list(gen([0, 0, 1, 0, 1, 1, 1, 0, 1, 1]))
[0, 0, 0, 0, 1, 1, 1, 1, 1, 1]

在这种方法中,我只返回第一个和最后一个项目而不进行检查,因为只有下一个或上一个项目,而不是两个项目。如果你愿意的话,你也可以在那里放一些支票。你知道吗

正如@madphestics所指出的,您根本不需要这个列表,只需为previouscurrentnext项使用一个变量即可:

def gen(x):
    x = iter(x)
    # Get the first item and simply yield it
    first = next(x)
    yield first

    cur, nxt = first, next(x)  # Initial current and next item
    for item in x:
        prev, cur, nxt = cur, nxt, item  # Update the previous, current and next item

        if cur != prev and cur != nxt:
            cur = prev
            yield prev

        else:
            yield cur

    # Simply yield the last item
    yield nxt

注意:这两种方法都会创建一个新列表,并且不会修改原始列表。你知道吗

您可能希望通过索引访问列表元素。在循环中,您可以通过对当前索引进行加法或减法来访问上一项和下一项。你知道吗

请记住,在列表中,可以使用hiter[0]hiter[1]、…,访问元素,在循环中如下所示:

for i in range(len(hiter)-1):
    print("The item is %s" % hiter[i])

这样就可以访问上一个和下一个,只需要处理边缘情况(防止索引超出范围)。一种方法是:

for i in range(len(hiter)):
    if 0 < i < (len(hiter) - 1):
        print("The items are %s, %s, %s" % (hiter[i-1], hiter[i], hiter[i+1]))
    elif i == 0:
        print("The items are %s, %s" % (hiter[i], hiter[i+1]))
    elif i == (len(hiter) - 1):
        print("The items are %s, %s" % (hiter[i-1], hiter[i]))

同样,可以使用相同的索引方法更改可变列表中的值。你知道吗

你把事情弄得太复杂了。相反,只需在循环中多次读取x

for idx in range(1, len(x)-1): # Consider using enumerate, it's a great idea
    curr = x[idx]
    prev = x[idx - 1]
    nxt = x[idx + 1]
    if (curr != prev) and (curr != nxt):
        print('prev %s - CURRENT %s - next %s' % (prev, curr, nxt))

相关问题 更多 >