简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM