SHARE
TWEET

Complete Unzip module

a guest Nov 17th, 2010 167 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. # -*- coding: utf-8 -*-
  2. # Author João S. O. Bueno <jsbueno(at)python.org.br>
  3. # Licensed under Creative Commons Attribution Required
  4.  
  5. def unzip(seq):
  6.     start = True
  7.     for next in seq:
  8.         if start:
  9.             result = [[] for _ in xrange(len(next))]
  10.             start = False
  11.         for i,v in enumerate(next):
  12.             result[i].append(v)
  13.     return result
  14.  
  15. def xunzip(seq):
  16.     it = iter(seq)
  17.     next = it.next()
  18.     width = len(next)
  19.     results = []
  20.     buffer_ = [{"tuple": next, "consumed": 0}]
  21.     # This is a list to workaround the non-existence
  22.     # of the "nonlocal" keyword in python 2
  23.     buffer_base = [0]
  24.     for i in xrange(width):
  25.         def freeze_i(j):
  26.             def unzipper():
  27.                 offset = 0
  28.                 while True:
  29.                     index = offset - buffer_base[0]
  30.                     if not (offset < len(buffer_) + buffer_base[0]):
  31.                         buffer_.append({"tuple": it.next(), "consumed": 0})
  32.                     buffer_[index]["consumed"] += 1
  33.                     value = buffer_[index]["tuple"][j]
  34.                     if buffer_[index]["consumed"] == width:
  35.                         buffer_.pop(0)
  36.                         buffer_base[0] += 1
  37.                     yield value
  38.                     offset += 1
  39.             unzipper.func_name = "seq_%d" % j
  40.             return unzipper
  41.         results.append(freeze_i(i)())
  42.     return results
  43.    
  44.  
  45. if __name__ == "__main__":
  46.     import random
  47.     a = zip(range(10), range(10,20), range(20,30))
  48.     print unzip(a)
  49.     b = xunzip(a)
  50.     finished_count = [0,0,0]
  51.     unpack = [-1, -1, -1]
  52.     while sum(finished_count) < len(b):
  53.         index = random.randrange(len(b))
  54.         try:
  55.             unpack[index] = b[index].next()
  56.             buffer_lenght = len(b[index].gi_frame.f_locals["buffer_"])
  57.         except StopIteration:
  58.             finished_count[index] = 1
  59.             buffer_lenght = "Unknown"
  60.         print unpack, "Buffer lenght: ", buffer_lenght
RAW Paste Data
Top