![](/img/trans.png)
[英]Powershell: Trying to combine two arrays that don't use the same columns
[英]Powershell: Combine single arrays into columns
鉴于:
$column1 = @(1,2,3)
$column2 = @(4,5,6)
我如何将它们组合到一个对象$ matrix中,该对象将显示为矩阵,而单个数组作为列:
column1 column2
------- -------
1 4
2 5
3 6
看来我今天所有的解决方案都需要计算出的属性。 尝试:
$column1 = @(1,2,3)
$column2 = @(4,5,6)
0..($column1.Length-1) | Select-Object @{n="Id";e={$_}}, @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}
Id Column1 Column2
-- ------- -------
0 1 4
1 2 5
2 3 6
如果数组的长度不相等,则可以使用:
$column1 = @(1,2,3)
$column2 = @(4,5,6,1)
$max = ($column1, $column2 | Measure-Object -Maximum -Property Count).Maximum
0..$max | Select-Object @{n="Column1";e={$column1[$_]}}, @{n="Column2";e={$column2[$_]}}
我不确定您是否需要Id
,因此我将其包含在第一个示例中以说明如何包含它。
好一点,也许:
$column1 = @(1,2,3)
$column2 = @(4,5,6,7)
$i=0
($column1,$column2 | sort length)[1] |
foreach {
new-object psobject -property @{
loess = $Column1[$i]
lowess = $column2[$i++]
}
} | ft -auto
loess lowess
----- ------
1 4
2 5
3 6
7
我想出了这个..但是似乎太冗长了。 还有什么短的吗?
&{
for ($i=0; $i -lt $y.Length; $i++) {
New-Object PSObject -Property @{
y = $y[$i]
loess = $smooth_loess[$i]
lowess = $smooth_lowess[$i]
}
}
} | Format-Table -AutoSize
这是mjolinor和Frode F.解决方案的组合。 我在使用Frode的使用选择对象的对象构造技巧时遇到了一些问题。 由于某种原因,它将输出可能代表对象引用的哈希值。 我一年只在PowerShell中编写几次代码,所以我只是提供此功能,以防其他人发现它有用(也许甚至是我未来的自己)。
$column1 = @(1,2,3)
$column2 = @(4,5,6,7)
$column3 = @(2,5,5,2,1,3);
$max = (
$column1,
$column2,
$column3 |
Measure-Object -Maximum -Property Count).Maximum;
$i=0
0..$max |
foreach {
new-object psobject -property @{
col1 = $Column1[$i]
col3 = $column3[$i]
col2 = $column2[$i++]
}
} | ft -auto
这是我今天创建的东西。 它的取值范围为0到列长度之一,然后将其映射到哈希列表。 使用选择将其转换为适当的表。
$table = 0..$ColA.Length | % { @{
ColA = $ColA[$_]
ColB = $ColB[$_]
}} | Select ColA, ColB
使用以下变量:
$ColA = @(1, 2, 3)
$ColB = @(4, 5, 6)
结果是
ColB ColA
---- ----
1 4
2 5
3 6
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.