基礎知識回顧——通用序列操作

來源:互聯網
上載者:User

標籤:知識   object   mod   映射   lis   gre   pytho   集合   ring   

資料結構是電腦儲存和組織資料的方式。Python中有三類四種內建的資料結構,分別是序列(List、Tuple)、映射(Dictionary)以及集合(Set)。

所有序列類型都可以進行某些特定的操作,這些操作包括:索引、分區、加、乘、迭代以及檢查某個元素是否屬於序列的成員(成員資格),還有計算序列長度、找出最大元素和最小元素的內建元素。

1.索引

1 >>> greeting = ("hello")2 >>> greeting[1]3 ‘e‘4 >>> greeting[-2]5 ‘l‘

 

2.分區

 1 >>> num = [1,5,4,7,0]  #從左往右分區起始索引為0,從右往左分區起始索引為-1 2 >>> num[1:3] 3 [5, 4] 4 >>> num[0:-2] 5 [1, 5, 4] 6 >>> num[2:-2] 7 [4] 8  9 #開始點的元素包括在結果之中,結束點的元素則不在分區之內;10 #對於一個正數步長,會從序列頭部開始向右提取元素,直到最後一個元素,對於負數步長,則從序列的尾部開始向左提取元素,直到第一個元素11 >>> num[0:4:2]            12 [1, 4]13 >>> num[::-2]14 [0, 4, 1]15 >>> num[2::-2]16 [4, 1]17 >>> num[:2:-2]18 [0]

 

3.加法:相同類型的序列才能進行串連操作

 1 >>> [1,2,3]+[4,5] 2 [1, 2, 3, 4, 5] 3 >>> ‘hello‘+‘world‘ 4 ‘helloworld‘ 5 >>> [1,2,3]+‘hello‘ 6  7 Traceback (most recent call last): 8   File "<pyshell#201>", line 1, in <module> 9     [1,2,3]+‘hello‘10 TypeError: can only concatenate list (not "str") to list

 

4.乘法

1 >>> ‘python,‘*52 ‘python,python,python,python,python,‘3 >>> seq = [None]*10    #初始化一個長度為10的列表4 >>> print seq5 [None, None, None, None, None, None, None, None, None, None]6 >>> print ‘!‘*5 + ‘Hello ,World‘ + ‘-‘*10    7 !!!!!Hello ,World----------

 

5.成員資格

 1 >>> ‘P‘in ‘Python‘ 2 True 3 >>> ‘p‘in ‘Python‘ 4 False 5  6 >>> ‘P‘in Python  #注意‘Python‘和Python區別 7  8 Traceback (most recent call last): 9   File "<pyshell#211>", line 1, in <module>10     ‘P‘in Python11 NameError: name ‘Python‘ is not defined

 

6.迭代:通過for迴圈來遍曆

 1 #並行迭代 2 >>> names = [‘ann‘,‘beth‘,‘tita‘,‘jane‘] 3 >>> ages = [‘21‘,‘19‘,‘18‘,‘22‘] 4 >>> zip(names,ages) 5 [(‘ann‘, ‘21‘), (‘beth‘, ‘19‘), (‘tita‘, ‘18‘), (‘jane‘, ‘22‘)] 6 >>> for name,age in zip(names,ages):      #zip可以處理不等長的序列 7     print name, ‘is‘ ,age ,‘years old‘ 8  9 ann is 21 years old10 beth is 19 years old11 tita is 18 years old12 jane is 22 years old13 14 #索引迭代15 >>> strings = ‘python‘16 >>> for index,string in enumerate(strings):17     if ‘3‘ in strings:18         strings[index] = ‘h‘19 20 #翻轉和排序迭代:reversed方法返回一個可迭代對象,sorted方法返回列表21 >>> sorted([2,0,7,5])22 [0, 2, 5, 7]23 >>> reversed(‘hello‘)24 <reversed object at 0x02FF8C70>25 >>> list(reversed(‘hello‘))26 [‘o‘, ‘l‘, ‘l‘, ‘e‘, ‘h‘]

 

7.序列長度、最大值、最小值

1 >>> num = [120,14,39]2 >>> len(num)3 34 >>> max(num)5 1206 >>> min(num)7 14

 

基礎知識回顧——通用序列操作

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.