0

假设我有这些值的列表:

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

我如何将每个第一个元素超过三个并将其附加到另一个列表中?例如,1,然后 2,然后 3...[1,2,3....31]

然后分别是第二个[91, 84, 86,......73]

第三个也是一样[70, 69, 68......63]

任何帮助都会很棒?

我现在正在使用循环并尝试将值附加到不同的列表中。

4

3 回答 3

9

使用步长值对列表进行切片:

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]
于 2013-04-02T20:44:39.987 回答
2

您可以使用逐步切片:

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

...或更一般地说,在一次通话中:

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)
于 2013-04-02T20:48:22.177 回答
1

另外的选择:

a, b, c = zip(*zip(*[iter(values)]*3))
于 2013-04-02T21:09:32.043 回答