日韩无码专区无码一级三级片|91人人爱网站中日韩无码电影|厨房大战丰满熟妇|AV高清无码在线免费观看|另类AV日韩少妇熟女|中文日本大黄一级黄色片|色情在线视频免费|亚洲成人特黄a片|黄片wwwav色图欧美|欧亚乱色一区二区三区

RELATEED CONSULTING
相關(guān)咨詢
選擇下列產(chǎn)品馬上在線溝通
服務(wù)時間:8:30-17:00
你可能遇到了下面的問題
關(guān)閉右側(cè)工具欄

新聞中心

這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
深入探討Python序列神奇之處

在Python編程語言這樣一款功能強大的面向?qū)ο笮陀嬎銠C通用語言中,有很多使用方法都和那些常見的額編程語言有很大的不同之處,比如今天為大家介紹的Python序列就是其中一個。首先,我們來學(xué)習(xí)如何使用索引來取得序列中的單個項目。這也被稱作是下標操作。每當你用方括號中的一個數(shù)來指定一個Python序列的時候,Python會為你抓取序列中對應(yīng)位置的項目。記住,Python從0開始計數(shù)。因此,shoplist[0]抓取第一個項目,shoplist[3]抓取shoplist序列中的第四個元素。#t#

索引同樣可以是負數(shù),在那樣的情況下,位置是從序列尾開始計算的。因此,shoplist[-1]表示序列的最后一個元素而shoplist[-2]抓取序列的倒數(shù)第二個項目。

切片操作符是Python序列名后跟一個方括號,方括號中有一對可選的數(shù)字,并用冒號分割。注意這與你使用的索引操作符十分相似。記住數(shù)是可選的,而冒號是必須的。

切片操作符中的第一個數(shù)(冒號之前)表示切片開始的位置,第二個數(shù)(冒號之后)表示切片到哪里結(jié)束。如果不指定第一個數(shù),Python就從序列首開始。如果沒有指定第二個數(shù),則Python會停止在序列尾。注意,返回的序列從開始位置 開始 ,剛好在 結(jié)束 位置之前結(jié)束。即開始位置是包含在序列切片中的,而結(jié)束位置被排斥在切片外。

這樣,shoplist[1:3]返回從位置1開始,包括位置2,但是停止在位置3的一個序列切片,因此返回一個含有兩個項目的切片。類似地,shoplist[:]返回整個序列的拷貝。

你可以用負數(shù)做切片。負數(shù)用在從序列尾開始計算的位置。例如,shoplist[:-1]會返回除了最后一個項目外包含所有項目的序列切片。

使用Python解釋器交互地嘗試不同切片指定組合,即在提示符下你能夠馬上看到結(jié)果。Python序列的神奇之處在于你可以用相同的方法訪問元組、列表和字符串。

 
 
 
  1. shoplist = ['apple', 'mango', 'carrot', 'banana']  
  2. # Indexing or 'Subscription' operation  
  3. print 'Item 0 is', shoplist[0]  
  4. print 'Item 1 is', shoplist[1]  
  5. print 'Item 2 is', shoplist[2]  
  6. print 'Item 3 is', shoplist[3]  
  7. print 'Item -1 is', shoplist[-1]  
  8. print 'Item -2 is', shoplist[-2]  
  9. # Slicing on a list  
  10. print 'Item 1 to 3 is', shoplist[1:3]  
  11. print 'Item 2 to end is', shoplist[2:]  
  12. print 'Item 1 to -1 is', shoplist[1:-1]  
  13. print 'Item start to end is', shoplist[:]  
  14. # Slicing on a string  
  15. name = 'swaroop' 
  16. print 'characters 1 to 3 is', name[1:3]  
  17. print 'characters 2 to end is', name[2:]  
  18. print 'characters 1 to -1 is', name[1:-1]  
  19. print 'characters start to end is', name[:]   
  20. $ python seq.py  
  21. Item 0 is apple  
  22. Item 1 is mango  
  23. Item 2 is carrot  
  24. Item 3 is banana  
  25. Item -1 is banana  
  26. Item -2 is carrot  
  27. Item 1 to 3 is ['mango', 'carrot']  
  28. Item 2 to end is ['carrot', 'banana']  
  29. Item 1 to -1 is ['mango', 'carrot']  
  30. Item start to end is ['apple', 'mango', 'carrot', 'banana']  
  31. characters 1 to 3 is wa  
  32. characters 2 to end is aroop  
  33. characters 1 to -1 is waroo  
  34. characters start to end is swaroop 

以上就是我們介紹的Python序列的全部內(nèi)容。


新聞標題:深入探討Python序列神奇之處
文章URL:http://www.5511xx.com/article/dpihchj.html