Skip to main content
 首页 » 编程设计

python之不正确的列表操作

2025年05月04日13yjmyzz

假设

>>> a = [1,2,3,4,5] 

我想要这样的输出

>>> b 
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]] 

这是我的代码:

class Child(object): 
    def get_lines(self): 
        a = [1,2,3,4,5]               
        b=[] 
        c=[] 
        j=0 
        for i in a: 
            print i 
            b.append(i) 
            print b 
            c.insert(j,b) 
 
            j=j+1 
        print c 
 
 
son= Child() 
son.get_lines() 

当我循环打印 list b 时,它给出:

1  
[1]  
2  
[1, 2] 
3   
[1, 2, 3]   
4   
[1, 2, 3, 4]  
5  
[1, 2, 3, 4, 5] 

输出是:

[[1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5], [1, 2, 3, 4, 5]] 

代码哪里出错了?

请您参考如下方法:

b 是始终相同的列表对象(注意我已将 print c 更改为 return c) :

>>> map(id, Child().get_lines()) 
... 
[49021616, 49021616, 49021616, 49021616, 49021616] 

c 包含对同一个列表的五个引用。我想你想要的是:

class Child(object): 
 
    def get_lines(self): 
        a = [1, 2, 3, 4, 5]               
        return [a[:x+1] for x in range(len(a))] 

这为每个步骤制作了 a 的部分(或全部)的浅拷贝:

>>> Child().get_lines() 
[[1], [1, 2], [1, 2, 3], [1, 2, 3, 4], [1, 2, 3, 4, 5]]