溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

python切片符號(hào)怎么用

發(fā)布時(shí)間:2021-08-10 12:30:38 來(lái)源:億速云 閱讀:121 作者:小新 欄目:編程語(yǔ)言

這篇文章主要為大家展示了“python切片符號(hào)怎么用”,內(nèi)容簡(jiǎn)而易懂,條理清晰,希望能夠幫助大家解決疑惑,下面讓小編帶領(lǐng)大家一起研究并學(xué)習(xí)一下“python切片符號(hào)怎么用”這篇文章吧。

a[start:stop]  # items start through stop-1
a[start:]      # items start through the rest of the array
a[:stop]       # items from the beginning through stop-1
a[:]           # a copy of the whole array

還有一個(gè)step值,可以與上述任何一個(gè)一起使用:

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

要記住的關(guān)鍵點(diǎn)是該:

1、stop值表示不在所選切片中的第一個(gè)值。之間的差stop和start是選擇的元素的數(shù)量(如果step是1,默認(rèn)值)。

2、startorstop可能是一個(gè)負(fù)數(shù),這意味著它從數(shù)組的末尾而不是開(kāi)頭開(kāi)始計(jì)數(shù)。

所以:

a[-1]    # last item in the array
a[-2:]   # last two items in the array
a[:-2]   # everything except the last two items

同樣,step可能是負(fù)數(shù):

a[::-1]    # all items in the array, reversed
a[1::-1]   # the first two items, reversed
a[:-3:-1]  # the last two items, reversed
a[-3::-1]  # everything except the last two items, reversed

如果項(xiàng)目少于您的要求,Python 對(duì)程序員是友好的。例如,如果你請(qǐng)求a[:-2]并且a只包含一個(gè)元素,你會(huì)得到一個(gè)空列表而不是錯(cuò)誤。有時(shí)您更喜歡錯(cuò)誤,因此您必須意識(shí)到這可能會(huì)發(fā)生。

以上是“python切片符號(hào)怎么用”這篇文章的所有內(nèi)容,感謝各位的閱讀!相信大家都有了一定的了解,希望分享的內(nèi)容對(duì)大家有所幫助,如果還想學(xué)習(xí)更多知識(shí),歡迎關(guān)注億速云行業(yè)資訊頻道!

向AI問(wèn)一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI