gpt4 book ai didi

.net - 当只有一个元素存在时,锯齿状的PowerShell数组将丢失尺寸

转载 作者:行者123 更新时间:2023-12-04 05:27:39 25 4
gpt4 key购买 nike

我具有以下PowerShell函数,该函数对1以外的任何输入均适用。如果我将其传递给1的输入,它将返回一个包含两个元素1,1的数组,而不是单个元素,该元素本身就是两个元素(1,1)的数组。

有什么想法可以使PowerShell返回带有一个本身就是数组的元素的锯齿状数组?

function getFactorPairs {
param($n)
$factorPairs = @()
$maxDiv = [math]::sqrt($n)
write-verbose "Max Divisor: $maxDiv"
for($c = 1; $c -le $maxDiv; $c ++) {
$o = $n / $c;
if($o -eq [math]::floor($o)) {
write-debug "Factor Pair: $c, $o"
$factorPairs += ,@($c,$o) # comma tells powershell to add defined array as element in existing array instead of adding array elements to existing array
}
}
return $factorPairs
}

这是我的测试,它的输出显示了问题所在。您可以看到第一个示例(输入为1)返回的长度为2,即使仅找到一个因素对。第二个示例(输入为6)工作正常,返回的长度为2,找到了两个因子对。
~» (getFactorPairs 1).length  
DEBUG: Factor Pair: 1, 1
2

~» (getFactorPairs 6).length
DEBUG: Factor Pair: 1, 6
DEBUG: Factor Pair: 2, 3
2

最佳答案

我在Windows XP上的PowerShell V2 CTP上对此进行了测试,并看到了与OP相同的结果。

问题似乎是PowerShell沿集合管道传递时“展平”集合的习惯。一个简单的解决方案是通过在要返回的表达式前面加上逗号运算符,从而将返回值包装在集合中:

return ,$factorPairs

有关更多详细信息,请参见Keith Hill的博客条目 Effective PowerShell Item 8: Output Cardinality - Scalars, Collections and Empty Sets - Oh My!

希望这可以帮助。

关于.net - 当只有一个元素存在时,锯齿状的PowerShell数组将丢失尺寸,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1390782/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com