通过创建一个元组切片 [英] Create a slice using a tuple

查看:144
本文介绍了通过创建一个元组切片的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有在Python任何方式使用元组作为指数分得一杯羹?
以下是无效的:

 >>>一个=范围(20)
>>> B =(5,12)#我的切片索引
>>>一个[B]#无效
>>> A [切片(B)]#无效
>>> A [B [0]:B [1]]#是一个尴尬的语法
[5,6,7,8,9,10,11]
>>> B1,B2 = b的
>>>一个[B1:B2]#看起来有点清洁
[5,6,7,8,9,10,11]

这似乎是一个合理的Python的语法,让我感到惊讶,我不能这样做。

(更新)
并将该溶液证明是:

 >>>一个[切片(* B)]
[5,6,7,8,9,10,11]


解决方案

您可以使用Python * ARGS 语法如下:

 >>>一个=范围(20)
>>> B =(5,12)
>>>一个[切片(* B)]
[5,6,7,8,9,10,11]

基本上,你告诉Python来把它解析 B 成单独的元素和各个元素传递给片()函数作为单独的参数。

Is there any way in python to use a tuple as the indices for a slice? The following is not valid:

>>> a = range(20)
>>> b = (5, 12)   # my slice indices
>>> a[b]          # not valid
>>> a[slice(b)]   # not valid
>>> a[b[0]:b[1]] # is an awkward syntax
[5, 6, 7, 8, 9, 10, 11]
>>> b1, b2 = b
>>> a[b1:b2]      # looks a bit cleaner
[5, 6, 7, 8, 9, 10, 11]

It seems like a reasonably pythonic syntax so I am surprised that I can't do it.

(update) And the solution turns out to be:

>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]

解决方案

You can use Python's *args syntax for this:

>>> a = range(20)
>>> b = (5, 12)
>>> a[slice(*b)]
[5, 6, 7, 8, 9, 10, 11]

Basically, you're telling Python to unpack the tuple b into individual elements and pass each of those elements to the slice() function as individual arguments.

这篇关于通过创建一个元组切片的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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