Python:列表列表 [英] Python: list of lists

查看:63
本文介绍了Python:列表列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

运行代码

listoflists = []
list = []
for i in range(0,10):
    list.append(i)
    if len(list)>3:
        list.remove(list[0])
        listoflists.append((list, list[0]))
print listoflists

返回

[([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 0), ([7, 8, 9], 1), ([7, 8, 9], 2), ([7, 8, 9], 3), ([7, 8, 9], 4), ([7, 8, 9], 5), ([7, 8, 9], 6), ([7, 8, 9], 7)]

所以不知何故,每个元组(列表)的第一个参数每次都在列表列表中更新,但第二个参数 list[0] 不是.有人可以解释这里发生了什么并提出解决此问题的方法吗?我想输出

so somehow the first argument of each tuple (list) is being updated each time in the list of lists, but the second argument list[0] is not. Can someone explain what's going on here and suggest a way to fix this? I'd like to output

[([0],0), ([0,1],0), ...

推荐答案

列表是一种可变类型 - 为了创建副本(而不是仅仅传递相同的列表),您需要明确地这样做:

Lists are a mutable type - in order to create a copy (rather than just passing the same list around), you need to do so explicitly:

listoflists.append((list[:], list[0]))

但是,list 已经是 Python 内置的名称 - 最好不要为您的变量使用该名称.这是一个不使用 list 作为变量名并进行复制的版本:

However, list is already the name of a Python built-in - it'd be better not to use that name for your variable. Here's a version that doesn't use list as a variable name, and makes a copy:

listoflists = []
a_list = []
for i in range(0,10):
    a_list.append(i)
    if len(a_list)>3:
        a_list.remove(a_list[0])
        listoflists.append((list(a_list), a_list[0]))
print listoflists


请注意,我演示了两种不同的方法来复制上面的列表:[:]list().

第一个,[:],是创建一个 slice(通常用于获取列表的一部分),它恰好包含整个列表,并且因此实际上是列表的副本.

The first, [:], is creating a slice (normally often used for getting just part of a list), which happens to contain the entire list, and thus is effectively a copy of the list.

第二个,list(),使用实际的list 类型构造函数来创建一个新的列表,它的内容与第一个相同列表.(我没有在第一个示例中使用它,因为您在代码中覆盖了该名称 - 这是您不想这样做的一个很好的示例!)

The second, list(), is using the actual list type constructor to create a new list which has contents equal to the first list. (I didn't use it in the first example because you were overwriting that name in your code - which is a good example of why you don't want to do that!)

这篇关于Python:列表列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆