List Splitting

Bill Pursell bill.pursell at gmail.com
Mon Aug 21 15:25:49 EDT 2006


Steven wrote:
> Hello everyone,
>
> I'm trying to work through a bit of a logic issue I'm having with a
> script I'm writing. Essentially, I have a list that's returned to
> me from another command that I need to regroup based on some aribitrary
> length.
>
> 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" ] ]
>
> The actual data isn't as simple as this, but if I can get the logic
> sorted out, I can handle the other part.
>
> Anyone have any good ideas on how to do this?

how about:
>>> t = [ "a", "b", "c", "n", "a", "a", "t", "t", "t" ]
>>> [t[i::3] for i in range(0,len(t)/3)]
[['a', 'n', 't'], ['b', 'a', 't'], ['c', 'a', 't']]
--
Bill Pursell




More information about the Python-list mailing list