你能使它更简单/优雅吗?
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
样本输出:
>>> zigzag('123456') (['1', '3', '5'], ['2', '4', '6'])
seq如您所说,如果是列表,则:
seq
def zigzag(seq): return seq[::2], seq[1::2]
如果seq是完全通用的可迭代对象,例如生成器:
def zigzag(seq): results = [], [] for i, e in enumerate(seq): results[i%2].append(e) return results