二维数组动态C#

时间:2018-12-30 15:53:52

标签: c# python-3.x

我是python开发人员,我想在C#上转换以下代码:

#long version
tab = []
for i in range(n):
    tab.append([])
    for j in range(n):
        tab[i].append(0)

#short version
tab = [[0]*n for _ in range(n)]

感谢您的帮助!

3 个答案:

答案 0 :(得分:1)

由于您需要动态列表大小,因此我建议使用C#通用List<>集合类型。

在此示例中,我创建了一个整数列表的列表。这与整数数组的动态数组(如果在C#中可能的话)非常相似。

List<List<int>>List<int>都可以增长并改变大小。就我的示例而言,我对每个列表中的元素数量进行了硬编码,但是不必固定。

这是一个示例代码,其中列出了一个整数列表:

    static void Main(string[] args)
    {

        List<List<int>> stuff = new List<List<int>>();

        for (int count = 0; count < 3; count++)
        {
            List<int> list = new List<int>();
            list.AddRange(new int[] { 1, 2, 4 });
            stuff.Add(list);
        }

        Console.WriteLine($"stuff is a list of {stuff.Count} items");
        Console.WriteLine($"the first list item in stuff has {stuff[0].Count} items");
        Console.ReadKey();
    }

以下是输出:

stuff is a list of 3 items 
the first list item in stuff has 3 items

希望这会有所帮助

答案 1 :(得分:0)

由于在C#数组中使用零初始化,因此该代码可以轻松转换为C#:

var n = 3;
var tab = new int[n, n];

答案 2 :(得分:0)

我测试了它的工作原理,但是它不是像python方法那样动态的:

int[][] newtab = new int[4][];
newtab[0] = new int[4] { 0,0,0,0 };
newtab[1] = new int[4] { 0, 0, 0, 0 };
newtab[2] = new int[4] { 0, 0, 0, 0 };
newtab[3] = new int[4] { 0, 0, 0, 0 };


for (int i = 0; i < newtab.Length; i++)
{
    for (int j = 0; j < newtab[i].Length; j++)
    {
        Console.Write(newtab[i][j]);
    }
    Console.WriteLine();
}