Python列表列表初始化 [英] Python list of list initialize

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

问题描述

我知道

[[]] * 10

将给出10个相同的空引用,并且

will give 10 references of the same empty, And

[[] for i in range(10)]

将给出10个空列表.但在此示例中:

will give 10 empty lists. But in this example:

def get_list(thing):
  return [thing for i in range(10)]
a = get_list([])
a[0].append(1)
print(a)

为什么再次显示结果

[[1], [1], [1], [1], [1], [1], [1], [1], [1], [1]]


与问题不同列表更改列表意外反映在子列表之间,我知道Python不会在[x]*10中进行复制.

Unlike question List of lists changes reflected across sublists unexpectedly , I understand that Python doesn't do copy in [x]*10.

但是为什么[][[] for i in range(10)]中是特殊的呢?我认为这是不一致的.

But why [] is special in [[] for i in range(10)] ? I think this is inconsistent. Instead of creating a empty list [] then pass to [ ___ for i in range(10)], Python take "[]" literally and execute "[]" for every i.

推荐答案

这是因为thing是相同的列表.

That is because thing is the same list.

[[] for i in range(10)]中,每次都会生成一个新列表.

In [[] for i in range(10)] a new list is generated every time.

[thing for i in range(10)]中,它始终是名为thing的列表.

In [thing for i in range(10)] it's always the list named thing.

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

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