开发者

Is there a more elegant / pythonic way to express this construct?

开发者 https://www.devze.com 2023-01-18 09:48 出处:网络
itemList = [\"a\",\"b\",\"c\",\"d\",\"e\",\"f\",开发者_StackOverflow\"g\",\"h\"] aa = \"NULL\" bb = \"NULL\"
itemList = ["a","b","c","d","e","f",开发者_StackOverflow"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)


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

or if you insist on printing:

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


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's elegant list comprehension is better for this problem. But just to explain why I'm not deleting this post:

You may one day want to generate windows from an iterator which is not a list. Since you can't take the length of an iterator without consuming it, (and also since some iterators may be infinite), and since taking slices from an iterator always return new values, you can't use the list comprehension ['_'.join(itemList[i:i+3]) for i in range(len(itemList)-2)] in this case.

Then the windows function is actually useful. For example:

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

yields

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


You could use a 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)

I don't have a Python interpreter available right now, but I think this should work.

0

精彩评论

暂无评论...
验证码 换一张
取 消