tags:

views:

130

answers:

3
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)
A: 

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.

Space_C0wb0y
AttributeError: type object 'buffer' has no attribute 'append'
Oli
Hm, this is strange, it says [here](http://docs.python.org/library/collections.html#collections.deque) that such a method should exist.
Space_C0wb0y
+9  A: 
>>> ['_'.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]))
SilentGhost
List comprehension wins for its conciseness. Thanks.
Toshio
+1  A: 
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
unutbu
`itertools.tee` creates list internally, so it would be much simpler and readable just to convert your `itemList` generator into a list and then use normal slicing.
SilentGhost
@SilentGhost: The internally generated list is only as large as the length of the tee. In this case, 3. The deques inside the list all get `popleft-ed` at the same rate, so they are also no larger than of length 3. The `windows` function can deal with an infinite iterator. The list comprehension can't.
unutbu