absurd
absurd

Reputation: 1115

Equally distribute a list in python

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']

Upvotes: 0

Views: 1744

Answers (2)

Ashwini Chaudhary
Ashwini Chaudhary

Reputation: 251051

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']]

Upvotes: 5

NPE
NPE

Reputation: 500673

Not exceedingly elegant, but here goes:

In [5]: a = ['a','b','c','d','e','f','g','h','i','j']

In [6]: [[a[i], a[len(a)//2+i]] for i in range(len(a)//2)]
Out[6]: [['a', 'f'], ['b', 'g'], ['c', 'h'], ['d', 'i'], ['e', 'j']]

If you're happy with a list of tuples, you could use zip():

In [7]: zip(a[:len(a)//2], a[len(a)//2:])
Out[7]: [('a', 'f'), ('b', 'g'), ('c', 'h'), ('d', 'i'), ('e', 'j')]

To convert this into a list of lists:

In [8]: map(list, zip(a[:len(a)//2], a[len(a)//2:]))
Out[8]: [['a', 'f'], ['b', 'g'], ['c', 'h'], ['d', 'i'], ['e', 'j']]

Upvotes: 2

Related Questions