【问题标题】:Is there a more elegant / pythonic way to express this construct?有没有更优雅/pythonic 的方式来表达这个结构?
【发布时间】:2010-09-30 13:04:42
【问题描述】:
itemList = ["a","b","c","d","e","f","g","h"]
aa = "NULL"
bb = "NULL"
cc = "NULL"
for item in itemList:
    aa = bb
    bb = cc
    cc = item
    if aa == "NULL":
        continue
    print "%s_%s_%s" % (aa, bb, cc)

【问题讨论】:

    标签: python list


    【解决方案1】:
    >>> ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)]
    ['a_b_c', 'b_c_d', 'c_d_e', 'd_e_f', 'e_f_g', 'f_g_h']
    

    或者如果您坚持打印:

    >>> for i in range(len(itemList)-2):
        print('_'.join(itemList[i:i+3]))
    

    【讨论】:

    • 列表理解因其简洁而胜出。谢谢。
    【解决方案2】:
    import itertools
    def windows(iterable, length=2):
        return itertools.izip(*(itertools.islice(it,n,None)
                for n,it in enumerate(itertools.tee(iterable,length))))
    
    itemList = ["a","b","c","d","e","f","g","h"]
    for group in windows(itemList,length=3):
        print('_'.join(group))
    

    SilentGhost 优雅的列表理解更适合这个问题。但只是为了解释为什么我不删除这篇文章:

    您可能有一天想要从不是列表的迭代器生成窗口。 因为你不能在不消耗迭代器的情况下获取它的长度,(而且因为一些迭代器可能是无限的),并且由于从迭代器中获取切片总是返回新值,所以你不能使用列表推导 ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)] in这种情况。

    那么windows 函数实际上是有用的。例如:

    def itemList():
        for x in range(8):
            yield str(x)
    for group in windows(itemList(),length=3):
        print('_'.join(group))
    

    产量

    0_1_2
    1_2_3
    2_3_4
    3_4_5
    4_5_6
    5_6_7
    

    【讨论】:

    • itertools.tee 在内部创建列表,因此将itemList 生成器转换为列表然后使用普通切片会更简单和可读。
    • @SilentGhost:内部生成的列表只有 tee 的长度。在这种情况下, 3. 列表中的双端队列都以相同的速率获得popleft-ed,因此它们的长度也不大于 3。windows 函数可以处理无限迭代器。列表推导不能。
    【解决方案3】:

    您可以使用deque

    itemList = ["a","b","c","d","e","f","g","h"]
    buffer = collections.deque(maxlen=3)
    for item in itemList:
        buffer.append(item)
        if len(buffer) != 3:
            continue
        print "%s_%s_%s" % (buffer)
    

    我现在没有可用的 Python 解释器,但我认为这应该可以。

    【讨论】:

    • AttributeError: type object 'buffer' has no attribute 'append'
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-25
    • 2012-08-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-12
    • 1970-01-01
    相关资源
    最近更新 更多