Can you make it more simple/elegant?
def zigzag(seq):
"""Return two sequences with alternating elements from `seq`"""
x, y = [], []
p, q = x, y
for e in seq:
p.append(e)
p, q = q, p
return x, y
Can you make it more simple/elegant?
def zigzag(seq):
"""Return two sequences with alternating elements from `seq`"""
x, y = [], []
p, q = x, y
for e in seq:
p.append(e)
p, q = q, p
return x, y
If seq
, as you say, is a list, then:
def zigzag(seq):
return seq[::2], seq[1::2]
If seq
is a totally generic iterable, such as possibly a generator:
def zigzag(seq):
results = [], []
for i, e in enumerate(seq):
results[i%2].append(e)
return results
This takes an iterator and returns two iterators:
import itertools
def zigzag(seq):
t1,t2 = itertools.tee(seq)
even = itertools.islice(t1,0,None,2)
odd = itertools.islice(t2,1,None,2)
return even,odd
If you prefer lists then you can return list(even),list(odd)
.