我有类似mylist = [1,2,3,4,5,6]
现在的列表,我需要遍历这个列表并创建 3 个这样的新列表
new1 = [1,4]
new2 = [2,5]
new3 = [3,6]
最简单的方法是什么?
我有类似mylist = [1,2,3,4,5,6]
现在的列表,我需要遍历这个列表并创建 3 个这样的新列表
new1 = [1,4]
new2 = [2,5]
new3 = [3,6]
最简单的方法是什么?
使用切片:
>>> mylist = [1,2,3,4,5,6]
>>> mylist[::3]
[1, 4]
>>> mylist[1::3]
[2, 5]
>>> mylist[2::3]
[3, 6]
>>> lis = range(1,21)
>>> new1, new2, new3 = [lis[i::3] for i in xrange(3)]
>>> new1
[1, 4, 7, 10, 13, 16, 19]
>>> new2
[2, 5, 8, 11, 14, 17, 20]
>>> new3
[3, 6, 9, 12, 15, 18]
如果您不熟悉切片,请阅读:解释 Python 的切片表示法
Maybe you should be using numpy
>>> import numpy as np
>>> arr = np.array([1,2,3,4,5,6])
>>> arr.reshape((arr.size//3, 3)).T
array([[1, 4],
[2, 5],
[3, 6]])