简体   繁体   English

如何跳过矩阵的每一行的第一个元素?

[英]How to skip first element in each line of matrix?

I have next matrix: 我有下一个矩阵:

1 4 2 1 3 5
2 3 1 2 4 5
3 4 5 3 2 1
4 5 1 3 4 2
5 3 2 4 5 1

and I am writing it from text file to 2d array starting from second line in file in this cycle: 在这个循环中,我将从文件的第二行开始将其从文本文件写入2d数组:

foreach (var line in File.ReadAllLines(@"input_5_5.txt", Encoding.GetEncoding(1250)).Skip(1))
            {
                    foreach (var col in line.Trim().Split(' '))
                    {
                        result[i, j] = int.Parse(col.Trim());
                        j++;
                    }
                    i++;
            }

I need to skip first element in each line of matrix and write to array result from second element in every line because first element in row of matrix is only number of row. 我需要跳过矩阵的每一行中的第一个元素,并写入每一行中第二个元素的数组result ,因为矩阵行中的第一个元素只是行数。

You should instead use (if you need to know which line/col). 您应该改用(如果您需要知道哪条线/列)。 Col is initialized with 1 since you don't need first column. 因为您不需要第一列,所以Col初始化为1。

string[] fileLines = System.IO.File.ReadAllLines(@"input_5_5.txt", Encoding.GetEncoding(1250));
for(int line = 0; line < fileLines.Length; line++)
{
    string[] splittedLines = fileLines[line].Trim().Split(' ');
    for(int col = 1; col < splittedLines.Length; col++)
    {
        // do whatever you want here
    }
}

I'd advise to simply skip foreach and use a regular for loop. 我建议您简单地跳过foreach并使用常规的for循环。 After trimming and splitting the line by space(s), simply skip the 1st element by initializing the index to 1 instead of 0. 在用行修剪和分割行之后,只需将索引初始化为1而不是0即可跳过第一个元素。

var cols = line.Trim().Split(' '); //use string split option to remove empty entries for robustness

for (int j = 1; j < cols.Length; j++) //note the j is initialized with 1, instead of 0

Note - All this assumes that either the data is known to be well formed, or you do appropriate bounds and error checks etc. 注意-所有这些都假设已知数据格式正确,或者您进行了适当的范围和错误检查等。

There are many variations on how to do this, but you want to start j at 1 instead of 0. that was you're missing element 0, which I believe if what you're after, so: 如何执行此操作有很多变体,但是您想将j从1而不是0开始。那是您缺少元素0,我相信如果您要这样做,那么:

foreach (var line in File.ReadAllLines(@"input_5_5.txt", Encoding.GetEncoding(1250)))
{
    int j = 1;
    foreach (var col in line.Trim().Split(' '))
    {
        result[i, j] = int.Parse(col.Trim());
        j++;
    }
    i++;
}

My exercise for this question, though some Linqs can still be shortcircuited, this may be more clear: 我对这个问题的练习,尽管某些Linq仍然可以短路,但可能更清楚:

    [TestMethod]
    public void LinqArraySkipFirstColumnAndLine()
    {
        var inputString = @"SkipThisLine
                            1 4 2 1 3 5
                            2 3 1 2 4 5 
                            3 4 5 3 2 1
                            4 5 1 3 4 2
                            5 3 2 4 5 1";

        char[] lineSeparator = new char[] { '\n' };
        char[] itemSeparator = new char[] { ' ' };

        var lines = inputString.Split(lineSeparator).Skip(1);
        Assert.AreEqual(5, lines.Count(), "Expect 5 rows");

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

        lines.ToList().ForEach(line => {
            int dummy = 0;
            var items = line.Trim()
                            .Split(itemSeparator,
                                   StringSplitOptions.RemoveEmptyEntries)
                            .Skip(1);
            Assert.AreEqual(5, items.Count(), "Expect 5 items each row");

            var row = items.Where(c => int.TryParse(c, out dummy))
                           .Select(w => dummy).ToList();
            matrix.Add(row);
        });

        var elements = from row in matrix
                       from cell in row
                       select cell;
        Assert.AreEqual(25, elements.Count(), "Expect 25 elements after flattening matrix");
    }

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

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