user2175034
user2175034

Reputation: 93

Appending over a loop onto different lists

Say I have a list of these values:

['1', '91', '70', '2', '84', '69', '3', '86', '68', '4', '84', '68', '5', '83', '70', '6', '80', '68', '7', '86', '73', '8', '89', '71', '9', '84', '67', '10', '83', '65', '11', '80', '66', '12', '86', '63', '13', '90', '69', '14', '91', '72', '15', '91', '72', '16', '88', '72', '17', '97', '76', '18', '89', '70', '19', '74', '66', '20', '71', '64', '21', '74', '61', '22', '84', '61', '23', '86', '66', '24', '91', '68', '25', '83', '65', '26', '84', '66', '27', '79', '64', '28', '72', '63', '29', '73', '64', '30', '81', '63', '31', '73', '63']

How would I take each first element over three and append it to another list? So for example, 1, and then 2, and then 3... making [1,2,3....31]

And then respectively the second being [91, 84, 86,......73]

and the same for the third [70, 69, 68......63]

Any help would be great?

I am using a loop now and trying to append the value to different lists.

Upvotes: 0

Views: 95

Answers (3)

georg
georg

Reputation: 214949

Another option:

a, b, c = zip(*zip(*[iter(values)]*3))

Upvotes: 1

Henry Keiter
Henry Keiter

Reputation: 17168

You can either use by-step slicing:

every_third = values[0::3]
every_third_plus_one = values[1::3]
every_third_plus_two = values[2::3]

...or more generally in a single call:

def separate_list(a, stepsize):
    '''Separate list a into a number of lists by stepping through 
    at the given stepsize.'''
    return [a[s::stepsize] for s in xrange(stepsize)]
print separate_list(values, 3)

Upvotes: 2

kindall
kindall

Reputation: 184131

Slice the list using a step value:

values = ['1', '91', '70', '2', '84', '69', '3', '86', '68', '4', '84', '68', 
          '5', '83', '70', '6', '80', '68', '7', '86', '73', '8', '89', '71', 
          '9', '84', '67', '10', '83', '65', '11', '80', '66', '12', '86',
          '63', '13', '90', '69', '14', '91', '72', '15', '91', '72', '16',
          '88', '72', '17', '97', '76', '18', '89', '70', '19', '74', '66',
          '20', '71', '64', '21', '74', '61', '22', '84', '61', '23', '86',
          '66', '24', '91', '68', '25', '83', '65', '26', '84', '66', '27',
          '79', '64', '28', '72', '63', '29', '73', '64', '30', '81', '63',
          '31', '73', '63']

values0 = values[0::3]
values1 = values[1::3]
values2 = values[2::3]

Upvotes: 9

Related Questions