Equally distribute a list in python -
suppose have following list in python:
a = ['a','b','c','d','e','f','g','h','i','j']
how distribute list this:
['a','f'] ['b','g'] ['c','h'] ['d','i'] ['e','j']
and how achieve if have list of unequal length , putting 'superfluous' items separate list?
i want able distribute elements of original list n parts in indicated manner.
so if n=3 be:
['a','d','g'] ['b','e','h'] ['c','f','i']
and 'superfluous' element in separate list
['j']
you can use zip
list comprehension:
def distribute(seq): n = len(seq)//2 #will work in both python 2 , 3 return [list(x) x in zip(seq[:n], seq[n:])] print distribute(['a','b','c','d','e','f','g','h','i','j']) #[['a', 'f'], ['b', 'g'], ['c', 'h'], ['d', 'i'], ['e', 'j']]
Comments
Post a Comment