相对于数组两端切分数组的惯用方式是什么? [英] What is the idiomatic way to slice an array relative to both of its ends?

查看:102
本文介绍了相对于数组两端切分数组的惯用方式是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Powershell的数组符号具有奇异的行为(尽管已记录),用于切片数组的末尾. 官方文档的这一部分很好地总结了这种奇怪之处:<​​/

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 rather well:

负数从数组末尾开始计数.例如,-1" 引用数组的最后一个元素.显示最后三个 数组的元素,键入:

Negative numbers count from the end of the array. For example, "-1" refers to the last element of the array. To display the last three elements of the array, type:

$a[-3..-1]

但是,使用此表示法时要小心.

However, be cautious when using this notation.

$a[0..-2]

此命令不引用数组的所有元素,除了 对于最后一个.它指的是第一个,最后一个和倒数第二个 数组中的元素.

This command does not refer to all the elements of the array, except for the last one. It refers to the first, last, and second-to-last elements in the array.

以下代码确认了怪异之处:

The following code confirms the bizarreness:

$a = 0,1,2,3
$a[1..-1]

确实输出了这个奇怪的结果:

Which indeed outputs this bizarre result:

1
0
3

所以,问题是,用一个相对于数组的开头和另一个相对于结尾的索引进行切片的惯用方式是什么?

So, the question is, what is the idiomatic way to slice with one index relative the start and another relative the end of the array?

请告诉我,这比这个丑陋的烂摊子还要好:

Please tell me it's something better than this ugly mess:

$a[1..($a.Count-1)]



描述我正在寻找的另一种方法是:此python表达式的惯用Powershell等效项:

Another way to describe what I'm looking for is this: The idiomatic Powershell equivalent of this python expression:

a=1,2,3,4
a[1:-1]

当然评估为(2,3)

推荐答案

如果要从数组末尾获取 n 个元素,只需从 -n 到 -1 :

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

由于$a[$i..$j]的工作方式,PowerShell不支持相对于数组的开始结束的索引.在Python表达式a[i:j]中,您分别指定ij作为第一个和最后一个索引.但是,在PowerShell ..中是范围运算符,它会生成一连串数字.在表达式$a[$i..$j]中,解释器首先将$i..$j评估为整数列表,然后使用该列表来检索这些索引上的数组元素:

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

如果您需要模拟Python的行为,则必须使用一个子表达式:

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

这篇关于相对于数组两端切分数组的惯用方式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆