danilobellini

Splitting iterables in Python

May 13th, 2014
223
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 2.26 KB | None | 0 0
  1. # Input to be split as iterables like [[interface, ip0, ip1, ...], [interface, ...], ...]
  2. data = ['eth0', '10.10.10.49', 'eth0:0', '192.168.1.149', 'eth0:1', '172.0.8.149', 'eth0:2', '192.168.10.149', 'eth1', '192.168.20.149', '127.0.0.1']
  3.  
  4. # Reduce
  5. from string import digits
  6. from functools import reduce # For Python 2 and 3 compatibility
  7. result = reduce(lambda a, b: a[:-1] + [a[-1] + [b]] if b[0] in digits else a + [[b]], data, [])
  8.  
  9. # String (bizarre, only works for ethernet interfaces)
  10. result = [("e" + blk).split() for blk in " ".join(data).split("e")[1:]]
  11.  
  12. # Reduce without lambda
  13. def func(a, b):
  14.     if b[0] in digits:
  15.         a[-1].append(b)
  16.     else:
  17.         a.append([b])
  18.     return a
  19. result = reduce(func, data, [])
  20.  
  21. # For loop (imperative) into "a"
  22. a = []
  23. for b in data:
  24.     if b[0] in digits:
  25.         a[-1].append(b)
  26.     else:
  27.         a.append([b])
  28.  
  29. ##############################
  30. ### But what we want is... ###
  31. ##############################
  32. result = split_from(lambda ch: ch[0] not in "0123456789", data)
  33.  
  34. # But how?
  35. def split_from(func, iterable):
  36.     blocks = []
  37.     for el in iterable:
  38.         if func(el):
  39.             blocks.append([el])
  40.         else:
  41.             blocks[-1].append(el)
  42.     return blocks
  43.  
  44. # And if we wanted a generator os lists?
  45. def split_from_gen(func, iterable):
  46.     it = iter(iterable)
  47.     blk = [next(it)]
  48.     for el in it:
  49.         if func(el):
  50.             yield blk
  51.             blk = [el]
  52.         else:
  53.             blk.append(el)
  54.     yield blk
  55.  
  56. # To convert it back to a list, you can use a @tolist decorator,
  57. # behave like map, filter, zip, range from Python 2 in Python 3
  58. from functools import wraps
  59. tolist = lambda func: wraps(func)(lambda *args, **kwargs: list(func(*args, **kwargs)))
  60.  
  61. # Why not a generator of generators?
  62. def split_from_gg(func, iterable):
  63.     it = iter(iterable)
  64.     mem = [next(it), True] # [lookahead element, has elements to yield]
  65.     def igf(): # Internal generator function
  66.         mem[1] = False
  67.         while True:
  68.             yield mem[0]
  69.             mem[0] = next(it)
  70.             if func(mem[0]):
  71.                 break
  72.         mem[1] = True
  73.     while mem[1]:
  74.         yield igf()
  75.  
  76. result = [list(el) for el in split_from_gg(lambda ch: ch[0] not in "0123456789", data)]
Advertisement
Add Comment
Please, Sign In to add comment