python从一个列表创建几个列表

时间:2013-06-08 10:06:55

标签: python python-2.7 list

我列出了类似mylist = [1,2,3,4,5,6]的内容,现在我需要遍历此列表并创建3个这样的新列表

 new1 = [1,4]
 new2 = [2,5]
 new3 = [3,6]

最简单的方法是什么?

2 个答案:

答案 0 :(得分:9)

使用切片:

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

如果您不熟悉切片,请仔细阅读:Explain Python's slice notation

答案 1 :(得分:2)

也许您应该使用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]])