【问题标题】:Randomize a List of Elements in a Powershell Array随机化 Powershell 数组中的元素列表
【发布时间】:2023-03-29 06:10:01
【问题描述】:

我正在寻找一个元素数组并在函数中返回该数组的随机版本。

例如:

function Randomize-List
{
   Param(
     [int[]]$InputList
   )
   ...code...
   return 10,7,2,6,5,3,1,9,8,4
}

$a = 1..10
Write-Output (Randomize-List -InputList $a)
10
7
2
...

你明白了。不知道如何解决这个问题,我是 Powershell 的新手,来自 Python 背景。

【问题讨论】:

    标签: arrays list powershell random


    【解决方案1】:

    您可以使用Get-Random 在 PowerShell 中执行此操作。

    function Randomize-List
    {
       Param(
         [array]$InputList
       )
    
       return $InputList | Get-Random -Count $InputList.Count;
    }
    
    $a = 1..10
    Write-Output (Randomize-List -InputList $a)
    

    【讨论】:

    • 你也可以使用$InputList | Sort-Object {Get-Random}[source]。
    猜你喜欢
    • 2010-10-23
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 2023-01-14
    • 1970-01-01
    • 1970-01-01
    • 2012-10-31
    相关资源
    最近更新 更多