簡體   English   中英

將Python腳本轉換為PowerShell

[英]Converting Python script to PowerShell

我正在嘗試將Python腳本轉換為PowerShell,但是我沒有任何Python經驗,並且花一點時間寫一些代碼。

def combinliste(seq, k):
    p = []
    i, imax = 0, 2**len(seq)-1
    while i<=imax:
        s = []
        j, jmax = 0, len(seq)-1
        while j<=jmax:
            if (i>>j)&1==1:
                s.append(seq[j])
            j += 1
        if len(s)==k:
            p.append(s)
        i += 1
    return p

我做了些什么,但我真的不知道這是否正確。 在PowerShell中+=是什么,和Python一樣嗎?

function combinliste {
    Param($seq, $k)
    $p = @()
    $i; $imax = 0, [Math]::Pow(2, $seq.Count) - 1
    while ($i -le $jmax) {
        $s = @()
        $j, $jmax = 0, $seq.Count - 1
        while ($j -le $jmax) {
            if ($i -shr $j -band 1 -eq 1) {
                $s + ($seq ???? #I don't know how to do it here
            }
            $j #humm.. 1
        }
        if ($s.Count -eq $k) {
            $p + $s
        }
        $i #humm.. 1
        return $p
    }
}

我嘗試了幾種變體,但迷路了。

function combinliste { param($seq,$k) 

$p = New-Object System.Collections.ArrayList

$i, $imax = 0, ([math]::Pow(2, $seq.Length) - 1)

while ($i -le $imax) {

     $s = New-Object System.Collections.ArrayList
     $j, $jmax = 0, ($seq.Length - 1)
     while ($j -le $jmax) {
         if((($i -shr $j) -band 1) -eq 1) {$s.Add($seq[$j]) | Out-Null}
         $j+=1
         }
     if ($s.Count -eq $k) {$p.Add($s) | Out-Null }
     $i+=1
   }

  return $p
}

$p = combinliste @('green', 'red', 'blue', 'white', 'yellow') 3

$p | foreach {$_ -join " | "}

append()方法就地更新數組。 PowerShell中的+運算符不會執行該操作。 您需要+=賦值運算符。

$s += $seq[$j]

$p += $s

另外,您可以使用ArrayList集合而不是普通數組:

$s = New-Object 'Collections.ArrayList'

並使用其Add()方法:

$s.Add($seq[$j]) | Out-Null

尾隨的Out-Null將禁止默認情況下Add()輸出的附加項的索引。


旁注:你可能需要把return $p while循環,和$i; $imax = ... $i; $imax = ...必須為$i, $imax = ...以便在一個語句中為兩個變量分配兩個值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM