【问题标题】:List of lists in Python -> Getting wrong outputPython中的列表列表->得到错误的输出
【发布时间】:2015-02-11 15:40:41
【问题描述】:

我正在尝试从循环中打印列表列表,但输出错误! 附加到较大列表的最后一个列表正在重复。

我期待的输出:

FINAL LIST:
[[(1, 2), (2, 3)],
 [(2, 3), (3, 4)]]

我得到的输出:

FINAL LIST:
[[(2, 3), (3, 4)],
 [(2, 3), (3, 4)]]

我在这里做错了什么?这是我的代码:

a = []
count = 1

#Function that generates some nos. for the list
def func():

    del a[:]
    for i in range(count,count+2):
        x = i
        y = i+1
        a.append((x,y))
    print '\nIn Function:',a    #List seems to be correct here
    return a


#List of lists
List = []
for i in range(1,3):
    b = func()             #Calling Function
    print 'In Loop:',b     #Checking the value, list seems to be correct here also
    List.append(b)
    count = count+1


print '\nList of Lists:'
print List

【问题讨论】:

  • 你认为del a[:] 会做什么?
  • del a[:] 每次调用函数时都会清空内部列表,以便添加新的元组集
  • 是的,它只会清空列表。但它仍然是同一个容器,每个函数调用都在修改同一个对象。所以,最后List 包含对列表a 的两个引用。只需将a 声明为局部变量。
  • del a[:] 没有任何意义。它会创建列表的新副本,然后立即将其删除。
  • @twasbrillig 不,它没有。 del a[:] 只是 empties a。这是突变,而不是重新分配。

标签: python list


【解决方案1】:

问题在于del a[:] 语句。其余的代码都很好。而不是这样做,在函数的开头放置一个空的a 列表,问题就消失了:

count = 1

#Function that generates some nos. for the list
def func():
    a = []
    for i in range(count,count+2):
        x = i
        y = i+1
        a.append((x,y))
    print '\nIn Function:',a    #List seems to be correct here
    return a


#List of lists
List = []
count = 1
for i in range(1,3):
    b = func()             #Calling Function
    print 'In Loop:',b     #Checking the value, list seems to be correct here also
    List.append(b)
    count = count + 1


print '\nList of Lists:'
print List

【讨论】:

    【解决方案2】:

    您将同一列表 (a) 多次附加到 List(您可以使用 print List[0] is List[1] 查看)。您需要创建多个列表,如下例所示:

    l = []
    for i in xrange(3):
        l.append([i, i+1])
    print l
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-04-16
      • 1970-01-01
      • 1970-01-01
      • 2014-11-03
      • 1970-01-01
      • 2021-01-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多