是否有更优雅/ pythonic的方式来表达这个结构?

时间:2010-09-30 13:04:42

标签: python list

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)

3 个答案:

答案 0 :(得分:9)

>>> ['_'.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]))

答案 1 :(得分:1)

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的优雅列表理解对这个问题更好。但只是为了解释我为什么不删除这篇文章:

您可能有一天想要从迭代器生成窗口,而迭代器不是列表。 因为你不能在没有消耗它的情况下获取迭代器的长度,(并且因为一些迭代器可能是无限的),并且因为从迭代器获取切片总是返回新值,所以你不能使用列表推导{{1}在这种情况下。

然后['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)]函数实际上很有用。例如:

windows

产量

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

答案 2 :(得分:0)

您可以使用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解释器,但我认为这应该有用。