What is the idiomatic way to slice an array relative to both of its ends?

前端 未结 7 1604
梦如初夏
梦如初夏 2021-02-06 20:35

Powershell\'s array notation has rather bizarre, albeit documented, behavior for slicing the end of arrays. This section from the official documentation sums up the bizarreness

7条回答
  •  天命终不由人
    2021-02-06 21:26

    If you want to get n elements from the end of an array simply fetch the elements from -n to -1:

    PS C:\> $a = 0,1,2,3
    PS C:\> $n = 2
    PS C:\> $a[-$n..-1]
    2
    3
    

    Edit: PowerShell doesn't support indexing relative to both beginning and end of the array, because of the way $a[$i..$j] works. In a Python expression a[i:j] you specify i and j as the first and last index respectively. However, in a PowerShell .. is the range operator, which generates a sequence of numbers. In an expression $a[$i..$j] the interpreter first evaluates $i..$j to a list of integers, and then the list is used to retrieve the array elements on these indexes:

    PS C:\> $a = 0,1,2,3
    PS C:\> $i = 1; $j = -1
    PS C:\> $index = $i..$j
    PS C:\> $index
    1
    0
    -1
    PS C:\> $a[$index]
    1
    0
    3
    

    If you need to emulate Python's behavior, you must use a subexpression:

    PS C:\> $a = 0,1,2,3
    PS C:\> $i = 1; $j = -1
    PS C:\> $a[$i..($a.Length+$j-1)]
    1
    2
    

提交回复
热议问题