python切片法星期显示代码_【试译】Python切片表示法

第一次翻译,尝试一个相对简单的吧。这是一个stackoverflow上关于切片的问题。

问题如下:

Do you have a good reference on the Python slice notation? To me, this notation needs a bit of picking up. It looks extremely powerful, but I haven't quite got my head round it and am looking for a good guide.

对于python切片的表示法,你有一个好的参考吗?对我来说,切片表示法有一点点难。虽然它看起来非常强大,但是我并没有完全理解它,一直在找一份关于切片好的指南。

获得最多支持的答案:

It's pretty simple really:

切片其实真的很简单:

a[start:end]# items start through end-1

a[start:]# items start through the rest of the array

a[:end]# items from the beginning through end-1

a[:]# a copy of the whole array

There is also the step value, which can be used with any of the above:

切片里有一个表示步长的参数,可以在上述任何情况下使用:

a[start:end:step]# start through not past end, by step

The key point to remember is that the :end value represents the first value that is not in the selected slice. So, the difference beween end and start is the number of elements selected (if step is 1, the default).

需要记住的关键点:终止值指向的元素不包含在切片内。因此,起始和终止的区别是被选择元素的数字(步长的默认参数值是1)。

(注:python总是左开右闭的,也就是说第一个参数包括,第二个参数不包括)

The other feature is that start or end may be a negative number, which means it counts from the end of the array instead of the beginning. So:

切片的另一个特征是起止和终止值可以是负数,这意味着你可以从序列右边而不是左边开始计数。So:

a[-1]# last item in the array

a[-2:]# last two items in the arraya[:-2]

# everything except the last two items

Python is kind to the programmer if there are fewer items than you ask for. For example, if you ask for a[:-2] and a only contains one element, you get an empty list instead of an error. Sometimes you would prefer the error, so you have to be aware that this may happen.

对于程序员来说,python是这样一种语言。如果存在的项目比你要求访问的少。举例而言,如果你要求访问 a[:-2],但是序列a只有一个元素。你会得到一个空序列而不是一个错误。有些时候你或许更希望得到错误,所以当这种情况(没有返回错误)发生时你必须保持警惕。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值