如何在python中分配列表列表

时间:2014-02-16 22:50:52

标签: python

所以这是一个例子。最后,[[]]应包含所有b列表。你需要任何其他细节???

a [[]]
b[]
n = 0;
for w in g:
b = ["1", "2", "3"]
a[0] = b // now a[0] contains ["1", "2", "3"]
do some changes to b
n += 1
......

next iteration of the loop
b = ["5", "6", "7"]
a[1] = b // now a[1] contains ["5", "6", "7"]
n +=1 (now n is 2)
and so on..


The error I get is - IndexError: list assignment index out of range

2 个答案:

答案 0 :(得分:1)

我想你想要:

a = []
for x in y:
    # stuff happens
    # ...
    a.append(b[:])

这将使a成为列表列表,其中每个子列表是来自一次循环迭代的列表b的副本。您不能指定超出列表末尾的内容,例如

a = []
a[0] = "foo"

因为a[0] 不存在,直到您appendextend列表为止。

答案 1 :(得分:0)

这是一个阴暗的尝试,因为你的OP非常模糊。

在行之间阅读:

while n < len(a):
    for i in b:
        a[n].append(i)
    n += 1
相关问题