简体   繁体   English

在 python 中创建具有 n 行的二维列表时出现问题

[英]Problem in creating a 2D list with n rows in python

I want to create an empty 2D list in python so in any row I can add multiple tuples as I want ex.我想在 python 中创建一个空的 2D 列表,因此在任何行中我都可以根据需要添加多个元组。 [ [ (2,3)], [ (4,5),(6,5),(9,0)] ] I only know that rows of the list will be n. [ [ (2,3)], [ (4,5),(6,5),(9,0)] ] 我只知道列表的行将是 n。 and after that I can manually append tuples as per the question.之后我可以根据问题手动 append 元组。 so I tried to create 2D list using:所以我尝试使用以下方法创建二维列表:

L = [ []*n ]  # n is number of rows ex. n = 5
print(L)      # It gives [[]] instead of [[], [], [], [], []]

Why?为什么?

use this code to create a 2D array:使用此代码创建一个二维数组:

L = [[] for _ in range(n)]

[] * n duplicates the elements present inside the list. [] * n复制列表存在的元素。 Since your list is empty, [] * n evaluates to [] .由于您的列表为空,因此[] * n的计算结果为[]

Additionally, [[]] * n will yield [[],[],[],[],[] for n = 5, but attempting to append an element to any of the inner lists will cause all the lists to contain the same element.此外, [[]] * n将在 n = 5 时产生[[],[],[],[],[] ,但尝试 append 将元素添加到任何内部列表将导致所有列表包含相同的元素。

>>> L = [[]]* 5
>>> L[0].append(1)
>>> L
[[1], [1], [1], [1], [1]]

This is due to the fact that each element of the outer list is essentially a reference to the same inner list.这是因为外部列表的每个元素本质上都是对同一个内部列表的引用。

Therefore, the idiomatic way to create such a list of lists is因此,创建这样一个列表列表的惯用方式是

L = [[] for _ in range(n)]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM