[英]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.