【问题标题】:How to add the numbers in two single-dimension arrays together and add that to a third list in powershell如何将两个单维数组中的数字相加并将其添加到powershell中的第三个列表中
【发布时间】:2021-12-25 16:47:15
【问题描述】:

请注意,我实际上是想以算术方式添加数字,而不是将它们连接起来,即 1+1 (2); 2+2 (4);所以在列表中添加数字。很抱歉造成混乱。

我有两个数组,需要将它们相加:

$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)

我需要遍历每个元素并将它们加在一起(算术),以便我得到:

1+2
2+3
3+4

在一个数组中。我怎样才能快速做到这一点?我正在使用 powershell 5.1。

【问题讨论】:

标签: arrays windows powershell


【解决方案1】:

您可以使用循环将每个数组中的数字连接,或者简单地将它们相加。在这种情况下,我们将使用 for 循环遍历数组中的每个项目:

$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
    for ($i = 0; $i -lt $Array1.Count; $i++) 
    {
        Write-Host -Object "$($Array1[$i]) + $($Array2[$i])"
    }
<# 
OutPut:
 1 + 2
 2 + 3
 3 + 4
 4 + 5
 5 + 1
#>

或者,如果您只是想添加它们:

$Array1 = @(1,2,3,4,5)
$Array2 = @(2,3,4,5,1)
    for ($i = 0; $i -lt $Array1.Count; $i++) 
    {
        $Array1[$i] + $Array2[$i]
    }
<# 
Output:
 3
 5
 7
 9 
 6
#>

【讨论】:

    【解决方案2】:

    我怎样才能快速做到这一点?

    假设这是您问题的重要部分,请将工作转移到已编译的 C# 代码中。亚伯拉罕 Zinala 的答案中的 for 循环对我来说在约 4 秒内运行了超过一百万个项目数组。 C# 中的相同循环运行时间约为 0.5 秒:

    Add-Type -Language CSharp @"
    using System;
    using System.Collections.Generic;
    
    namespace AddHelper
    {
        public static class Adder
        {
            public static int[] AddArrays(int[] array1, int[] array2) 
            {
                int[] result = new int[array1.Length];
                for (int i = 0; i < array1.Length; i++) {
                    result[i] = array1[i] + array2[i];
                }
                return result;
            }
        }
    }
    "@;
    
    $result = [AddHelper.Adder]::AddArrays($Array1, $Array2)
    

    将 PowerShell 和 C# 中的所有内容从使用数组转换为使用 [System.Collections.Generic.List[int]] 可将大约 500 毫秒降至大约 430 毫秒。

    【讨论】:

      猜你喜欢
      • 2016-11-13
      • 1970-01-01
      • 1970-01-01
      • 2015-07-29
      • 1970-01-01
      • 2012-10-19
      • 1970-01-01
      • 2020-01-14
      • 1970-01-01
      相关资源
      最近更新 更多