Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # -*- coding: utf-8 -*-
- # Author João S. O. Bueno <jsbueno(at)python.org.br>
- # Licensed under Creative Commons Attribution Required
- def unzip(seq):
- start = True
- for next in seq:
- if start:
- result = [[] for _ in xrange(len(next))]
- start = False
- for i,v in enumerate(next):
- result[i].append(v)
- return result
- def xunzip(seq):
- it = iter(seq)
- next = it.next()
- width = len(next)
- results = []
- buffer_ = [{"tuple": next, "consumed": 0}]
- # This is a list to workaround the non-existence
- # of the "nonlocal" keyword in python 2
- buffer_base = [0]
- for i in xrange(width):
- def freeze_i(j):
- def unzipper():
- offset = 0
- while True:
- index = offset - buffer_base[0]
- if not (offset < len(buffer_) + buffer_base[0]):
- buffer_.append({"tuple": it.next(), "consumed": 0})
- buffer_[index]["consumed"] += 1
- value = buffer_[index]["tuple"][j]
- if buffer_[index]["consumed"] == width:
- buffer_.pop(0)
- buffer_base[0] += 1
- yield value
- offset += 1
- unzipper.func_name = "seq_%d" % j
- return unzipper
- results.append(freeze_i(i)())
- return results
- if __name__ == "__main__":
- import random
- a = zip(range(10), range(10,20), range(20,30))
- print unzip(a)
- b = xunzip(a)
- finished_count = [0,0,0]
- unpack = [-1, -1, -1]
- while sum(finished_count) < len(b):
- index = random.randrange(len(b))
- try:
- unpack[index] = b[index].next()
- buffer_lenght = len(b[index].gi_frame.f_locals["buffer_"])
- except StopIteration:
- finished_count[index] = 1
- buffer_lenght = "Unknown"
- print unpack, "Buffer lenght: ", buffer_lenght
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement