0

我有一个动态组:例如,这次我们有一个包含 20 个项目的列表.. 我想在 4 个单独的列表中列出这个列表,其中包含 5 个项目,这样的事情在我的脑海中..

a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
z = len(a)/4
b = []
for i in range(z)

在我不知道我应该做什么之后......

我做了这样的事情,但这是完全错误的:

for i in range(len(a)):
    for j in range(z):
        b.append(a)

这是我的代码:

import maya.cmds as cm
import random as random
myList = cm.ls(sl = True)
random.shuffle(myList)
b = [myList[i:i+5] for i in range(0, len(myList), 5)]
for i in b:
    print str(i)+".v"

结果是:

[u'curve13', u'curve26', u'curve5', u'curve40', u'curve17'].v

但是我需要:

[u'curve13.v', u'curve26.v', u'curve5.v', u'curve40.v', u'curve17.v'].v
4

1 回答 1

0

使用切片操作:

>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>>> b = [a[i:i+5] for i in range(0, len(a), 5)]
>>> b
[[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20]]
>>> b[2][3]
14

更新对评论的回应

访问项目

>>> for item in b[2]: print '{}.v'.format(item)
...
11.v
12.v
13.v
14.v
15.v

更新2

>>> a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]
>>> n = len(a)
>>> b = [a[n*i/4:n*(i+1)/4] for i in range(4)]
>>> c, d, e, f = b
>>> c
[1, 2, 3, 4, 5]
>>> d
[6, 7, 8, 9, 10]
>>> e
[11, 12, 13, 14, 15]
>>> f
[16, 17, 18, 19, 20]
于 2013-08-02T18:28:59.943 回答