List Splitting

Tim Chase python.list at tim.thechases.com
Mon Aug 21 15:28:43 EDT 2006


> For the purposes of this question, the list will be:
> 
> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ]
> 
> Now, I know that every 3rd element of the list belongs together:
> 
> Group 1 = 0, 3, 6
> Group 2 = 1, 4, 7
> Group 3 = 2, 5, 8
> 
> I'm trying to sort this list out so that I get a list of lists that
> contain the correct elements:
> 
> Goal = [ [ "a", "n", "t"], [ "b", "a", "t"],
> ["c", "a", "t" ] ]

Well, the following worked for me:

 >>> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ]
 >>> stride = 3
 >>> Goal = [t[i::stride] for i in range(stride)]
 >>> Goal
[['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']]


Or, if you like, in this example:

 >>> [''.join(t[i::stride]) for i in range(stride)]
['ant', 'bat', 'cat']

if that's of any use.

-tkc








More information about the Python-list mailing list