第一句子网 - 唯美句子、句子迷、好句子大全
第一句子网 > python变量的使用_python – 如何在变量中使用冒号(:)

python变量的使用_python – 如何在变量中使用冒号(:)

时间:2020-06-02 02:57:18

相关推荐

python变量的使用_python – 如何在变量中使用冒号(:)

你想要一个

slice() object:

index = slice(0, 2)

print(somelist[index])

slice()模拟您可以在[start:stop:stride]预订语法中指定的start,stop和stride值作为对象.

从文档:

Return a 07001 object representing the set of indices specified by range(start, stop, step). The start and step arguments default to None. Slice objects have read-only data attributes start, stop and step which merely return the argument values (or their default).

在幕后,Python实际上在调用自定义__getitem__方法时将订阅转换为slice()对象:

>>> class Foo(object):

... def __getitem__(self, item):

... return item

...

>>> Foo()[42:81:7]

slice(42, 81, 7)

>>> Foo()[:42]

slice(None, 42, None)

一个可行的替代方案是将start和stop存储为单独的值:

startindex = 0

stopindex = 2

print(somelist[start:stop])

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。