使用slice()切片而没有停止值

时间:2018-02-22 10:15:52

标签: python

使用python的内置[:]类是否有slice的等价物?

In [8]: 'abcdef'[:3]
Out[8]: 'abc'

In [9]: 'abcdef'[slice(3)]
Out[9]: 'abc'

In [10]: 'abcdef'[:]
Out[10]: 'abcdef'

In [11]: 'abcdef'[slice()]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-11-9afb03fec62a> in <module>()
----> 1 'abcdef'[slice()]

TypeError: slice expected at least 1 arguments, got 0

2 个答案:

答案 0 :(得分:5)

当然,以下任何一项都是等同的:

>>> seq = [1,2,3,4]
>>> seq[slice(None)]
[1, 2, 3, 4]
>>> seq[slice(None, None)]
[1, 2, 3, 4]
>>> seq[slice(None, None, None)]
[1, 2, 3, 4]

答案 1 :(得分:3)

您可以使用None,默认值:

>>> 'abcdef'[:]
'abcdef'
>>> 'abcdef'[None:]
'abcdef'
>>> 'abcdef'[None:None]
'abcdef'
>>> 'abcdef'[None:None:None]
'abcdef'
>>> 'abcdef'[slice(None)]
'abcdef'
>>> 'abcdef'[slice(None, None)]
'abcdef'
>>> 'abcdef'[slice(None, None, None)]
'abcdef'