在占位符的开始或结束处离开

2024-06-12 22:22:24 发布

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

以列表为例:

a = [255, 255, 1, 255, 255, 255, 1, 2, 255, 255, 2, 255, 255, 3, 255, 3, 255, 255, 255]

255是其中的一个特殊值。它是一个占位符。在

我做了一个生成器来替换列表中的一些占位符。它按预期工作。在

但我不需要处理开始占位符[255, 255和结束占位符{},并将它们原封不动地生成。在

所以,我试着修改发电机来解决这个问题:

Python 2.7版

^{pr2}$

将中间值转换为list只是为了便于理解代码:

>>>iterable
[255,1,255,255,1,255,255,255,2,2,255,255,255,2,2,3,255,255,255,3,255,255]

>>>it = enumerate(iterable)
[(0, 255), (1, 1), (2, 255), (3, 255), (4, 1), (5, 255), (6, 255), (7, 255), (8, 2), (9, 2), (10, 255), (11, 255), (12, 255), (13, 2), (14, 2), (15, 3), (16, 255), (17, 255), (18, 255), (19, 3), (20, 255), (21, 255)]

>>>it = ifilterfalse(lambda x: x[1]==placeholder, it)
[(1, 1), (4, 1), (8, 2), (9, 2), (13, 2), (14, 2), (15, 3), (19, 3)]

>>>list(enumerate(window(it,2)))
[(0, ((1, 1), (4, 1))), (1, ((4, 1), (8, 2))), (2, ((8, 2), (9, 2))), (3, ((9, 2), (13, 2))), (4, ((13, 2), (14, 2))), (5, ((14, 2), (15, 3))), (6, ((15, 3), (19, 3)))]

因此,如您所见,list(enumerate(window(it,2)))包含前导非占位符值(0, ((**1**, 1), (4, 1))),的索引,但它不包含初始迭代器有多少个尾随占位符的信息:list(enumerate(window(it,2)))以这个值结束(6, ((15, 3), (**19**, 3))),该值只有最后一个非占位符值的索引,这并没有给出剩余占位符的信息。在

我设法通过依赖it = enumerate(iterable)来处理前导占位符,该占位符产生初始迭代器值的位置,该初始迭代器值在ifilterfalse产生的第一个值中保持不变。在

但我花了相当多的时间试图弄清楚如何对尾部占位符做同样的事情。问题是ifilterfalse只是吞并了enumerate(iterable)的最后一个占位符值,我看不到访问它们的方法(因为第一个生成的ifilterfalse的值包含了enumerate(iterable)值的索引,所以前导占位符是可能的)。在

问题

什么是更正此代码以处理尾部占位符的最佳方法?在

由于目标不是通过各种方式创建代码(我已经使用了不同的技术done it),所以我希望通过对代码进行一点修改来解决任务,而不是完全重写它。在

与其说是真正的任务,不如说是训练。在

其他信息

window是来自here的代码。在

我的代码几乎与@nye17在this应答中所做的相同。但在这段代码中,作者对初始列表进行了适当的修改。我想创建一个生成器,它将产生与代码中的结果列表相同的值。在

此外,我希望我的生成器接受任何iterables作为参数,而不仅仅是列表(例如,它可能接受迭代器,它逐个读取文件中的值)。由于只将列表作为参数,任务变得更简单,因为我们可以从末尾扫描列表。在

这不是我生活中必须解决的真正任务。只是为了训练。在

完整代码http://codepad.org/9UJ9comY


Tags: 方法代码信息列表参数itwindowiterable
3条回答
def replace(it, process, placeholder):
    it = iter(it)
    while True:
        item = it.next()
        if item == placeholder:
            yield item
        else:
            yield process(item)
    pcount = 0
    try:
        while True:
            item = it.next()
            if item == placeholder:
                pcount += 1
            else:
                for i in range(pcount):
                    yield process(placeholder)
                pcount = 0
                yield process(item)
    except StopIteration:
        for i in range(pcount):
            yield placeholder

这样使用:

^{pr2}$

我想出的最简单的解决方案是通过另一个生成器来处理it = enumerate(iterable),它只保存它最后返回的值。在

因此,我在it = enumerate(iterable)(在replace函数内)之后添加了以下代码:

def save_last(iterable):
        for i in iterable:
            yield i
        replace.last_index = i[0] #Save the last value
it = save_last(it)

iterable用尽后,生成器的最后一个运算符将生成值的索引(即i[0]保存为enumerate将其存储在tuplee的0位置)作为replace属性(因为replace函数是类的实例,可以有局部变量)。在

it被包装在新创建的生成器save_last中。在

在函数的末尾,我添加了使用replace.last_index变量中保存的索引的代码。在

^{pr2}$

完整代码:

from __future__ import print_function
from  itertools import tee, izip, ifilterfalse


def window(iterable,n):
    els = tee(iterable,n)
    for i,el in enumerate(els):
        for _ in range(i):
            next(el, None)
    return izip(*els)


def replace(iterable,placeholder=255):
    it = enumerate(iterable)

    def save_last(iterable):
        for i in iterable:
            yield i
        replace.last_index = i[0] #Save the last value
    it = save_last(it)

    it = ifilterfalse(lambda x: x[1]==placeholder, it)
    for i,(left,right) in enumerate(window(it,2)):
        if i==0:
            for j in range(left[0]):
                yield placeholder
        yield left[1]
        if right[0]>left[0]+1:
            if left[1]==right[1]:
                for _ in range(right[0]-left[0]-1):
                    yield left[1]
            else:
                for _ in range(right[0]-left[0]-1):
                    yield placeholder
    yield right[1]
    if right[0]<replace.last_index:
        for i in range(replace.last_index-right[0]):
            yield placeholder


a = [255,1,255,255,1,255,255,255,2,2,255,255,255,2,2,3,255,255,255,3,255,255]        
print('\nInput: {}'.format(a))
output = list(replace(a))
print('Proram output: {}'.format(output))
print('Goal output  : {}'.format([255,1,1,1,1,255,255,255,2,2,2,2,2,2,2,3,3,3,3,3,255,255]))

如预期的那样工作:

Input: [255, 1, 255, 255, 1, 255, 255, 255, 2, 2, 255, 255, 255, 2, 2, 3, 255, 255, 255, 3, 255, 255]
Proram output: [255, 1, 1, 1, 1, 255, 255, 255, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 255, 255]
Goal output  : [255, 1, 1, 1, 1, 255, 255, 255, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 255, 255]

我唯一不喜欢的是用C ifilterfalse和用Python编写的save_last编写的非常高效的组合。在

def replace(it, placeholder):
    while True:
        curr = it.next()
        if curr == placeholder:
            yield curr
        else:
            break

    yield curr

    try:
        cache = []
        while True:      
            curr = it.next()

            if curr == placeholder:
                cache.append(curr)
            else:
                for cached in cache:
                    yield TRANSFORM(cached)
                yield curr
                cache = []

    except StopIteration:
        for cached in cache:
            yield cache

相关问题 更多 >