如何处理列表列表? [英] How do I handle a List of Lists?

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

问题描述

有人能解释一下这段代码出了什么问题吗?从代码中(至少我自己)会期望在运行此代码后,数字列表看起来像 numbers = [[0], [1]],但它看起来像 数字= [[0,1], [0,1]].

Could someone explain what goes wrong in this piece of code? From the code one (at least myself) would expect that after having ran this code the number list would look like numbers = [[0], [1]], but instead it looks like numbers= [[0,1], [0,1]].

void main() {
  int n = 2;
  List<List<int>> numbers = new List.filled(n, []);
  
  for(int i=0; i<n; i++)
    for(int j=i+1; j<n; j++ ){
      numbers[i].add(0);
      numbers[j].add(1);
    }
}

推荐答案

似乎列表中的每个元素都填充了相同的 [] 实例.如果你然后执行 numbers[0].add(0); numbers[0]numbers[1] 显示添加的 0 因为它们引用了相同的列表实例.

It seems each element of your list is filled with the same instance of []. If you then do numbers[0].add(0); numbers[0] and numbers[1] show the added 0 because they reference the same list instance.

将列表初始化更改为

List<List<int>> numbers = new List.generate(n, (i) => []);

显示您的预期行为.

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

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