3

是否有允许从 Powershell 中的多维数组中检索单列的函数、方法或语言构造?

$my_array = @()
$my_array += ,@(1,2,3)
$my_array += ,@(4,5,6)
$my_array += ,@(7,8,9)

# I currently use that, and I want to find a better way:
foreach ($line in $my_array) {
    [array]$single_column += $line[1]    # fetch column 1
}
# now $single_column contains only 2 and 5 and 8

我的最终目标是从一列中找到不重复的值。

4

3 回答 3

4

抱歉,我认为这样的事情不存在。我会去:

@($my_array | foreach { $_[1] })

为了快速找到唯一值,我倾向于使用哈希表键 hack:

$UniqueArray = @($my_array | foreach -Begin { 
    $unique = @{} 
} -Process { 
    $unique.($_[1]) = $null
} -End { 
    $unique.Keys 
})

显然它有它的局限性......

于 2012-06-24T18:03:45.263 回答
2

要提取一列:

$single_column = $my_array | foreach { $_[1] }

要提取任何列:

$some_columns = $my_array | foreach { ,@($_[2],$_[1]) }   # any order

要从一列中查找非重复值:

$unique_array = $my_array | foreach {$_[1]} | sort-object -unique
# caveat: the resulting array is sorted,
# so BartekB have a better solution if sort is a problem
于 2012-06-24T19:15:49.387 回答
0

I tried @BartekB's solution and it worked for me. But for the unique part I did the following.

@($my_array | foreach { $_[1] } | select -Unique)

I am not very familiar with powershell but I am posting this hoping it helps others since it worked for me.

于 2021-03-15T06:54:16.630 回答