Suppose I have the following list in python:
a = ['a','b','c','d','e','f','g','h','i','j']
How do I distribute the list like this:
['a','f']
['b','g']
['c','h']
['d','i']
['e','j']
And how do I achieve this if I have a list of unequal length and putting the 'superfluous' items into a separate list?
I want to be able to distribute the elements of the original list into n parts in the indicated manner.
So if n=3 that would be:
['a','d','g']
['b','e','h']
['c','f','i']
and the 'superfluous' element in a separate list
['j']
解决方案
You can use zip with a list comprehension:
def distribute(seq):
n = len(seq)//2 #Will work in both Python 2 and 3
return [list(x) for 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']]