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

前端 未结 7 1431
梦如初夏
梦如初夏 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:25

    $arr = @(10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10)

    $arr | Select-Object -First 5 | Select-Object -Index (@(0..4) | Where-Object { $_ % 2 -eq 0}) 
    $arr | Select-Object -Last 5
    $arr | Select-Object -Unique
    $arr | Sort-Object | Select-Object -Unique
    $arr | Where-Object {  $_ % 5 -eq 0 } | Sort-Object | Select-Object -Unique
    $arr | Select-Object -First ($arr.Count - 3)
    

    Actually code speaks for itself. I event don't need to explain.

    However, 1) Provide the first five elements, but each second of those five. Equal to arr[:5:2] in Python 2) Get the last five elements. 3) Gives unique elements 4) Firstly sort and then provide unique 5) Gives only elements which equal 0 by applying modulo of 5, sort, unique. 5) Provide the first count of elements in that array minus three elements only.

提交回复
热议问题