Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # Input to be split as iterables like [[interface, ip0, ip1, ...], [interface, ...], ...]
- 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']
- # Reduce
- from string import digits
- from functools import reduce # For Python 2 and 3 compatibility
- result = reduce(lambda a, b: a[:-1] + [a[-1] + [b]] if b[0] in digits else a + [[b]], data, [])
- # String (bizarre, only works for ethernet interfaces)
- result = [("e" + blk).split() for blk in " ".join(data).split("e")[1:]]
- # Reduce without lambda
- def func(a, b):
- if b[0] in digits:
- a[-1].append(b)
- else:
- a.append([b])
- return a
- result = reduce(func, data, [])
- # For loop (imperative) into "a"
- a = []
- for b in data:
- if b[0] in digits:
- a[-1].append(b)
- else:
- a.append([b])
- ##############################
- ### But what we want is... ###
- ##############################
- result = split_from(lambda ch: ch[0] not in "0123456789", data)
- # But how?
- def split_from(func, iterable):
- blocks = []
- for el in iterable:
- if func(el):
- blocks.append([el])
- else:
- blocks[-1].append(el)
- return blocks
- # And if we wanted a generator os lists?
- def split_from_gen(func, iterable):
- it = iter(iterable)
- blk = [next(it)]
- for el in it:
- if func(el):
- yield blk
- blk = [el]
- else:
- blk.append(el)
- yield blk
- # To convert it back to a list, you can use a @tolist decorator,
- # behave like map, filter, zip, range from Python 2 in Python 3
- from functools import wraps
- tolist = lambda func: wraps(func)(lambda *args, **kwargs: list(func(*args, **kwargs)))
- # Why not a generator of generators?
- def split_from_gg(func, iterable):
- it = iter(iterable)
- mem = [next(it), True] # [lookahead element, has elements to yield]
- def igf(): # Internal generator function
- mem[1] = False
- while True:
- yield mem[0]
- mem[0] = next(it)
- if func(mem[0]):
- break
- mem[1] = True
- while mem[1]:
- yield igf()
- 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