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])
總結
以上是生活随笔為你收集整理的python变量的使用_python – 如何在变量中使用冒号(:)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: mysql修改最大文件数_mysql更改
- 下一篇: websocket python爬虫_p