python基礎學習筆記(三)

來源:互聯網
上載者:User

標籤:學習   box   返回結果   org   ace   user   輸入   data   構建   

序列概覽

  Python 包含6 種內建的序列,這裡重點討論最常用的兩種類型:列表和元組。

  列表與元組的主要區別在於,列表可以修改,元組則不能。也就是說如果要根據要求來添加元素,那麼列表可以會更好用;而出於某些原因,序列不能修改的時候,使用元組則更為合適。

在操作一組數值的時候,序列很好用。可以用序列表示資料庫中一個人的資訊---第一1是姓名,第2個元素是年齡。根據上述內容編寫一個列表。

>>> hu=[‘huhu‘,25]

 

同時,序列也可以包含其他的序列,因此,構建如下一個人員的資訊的列表也是可的,這個列表就是你的資料庫:

>>> huhu = [‘huhu‘,25]>>> chongshi = [‘chongshi‘,32]>>> database = [huhu,chongshi]>>> database[[‘huhu‘, 25], [‘chongshi‘, 32]]

 

 

通用序列操作

  所有序列類型都可以進行某些特定的操作。這些操作包括:索引(indexing)、分區(sliceing)、加(adding)、乘(multiplying)以及檢查某個元素是否屬於序列的成員(成員資格)。

 

索引

序列中的所有元素都是有編號的-----從0 開始遞增。這些元素可以通過編號分別訪問,如下所示:

>>> greeting = ‘chongshi‘>>> greeting[0]‘c‘>>> greeting[2]‘o‘

 

使用負數索引時,python 會從右邊,也就是從最後1個元素開始計數。最後1個元素的位置編號是-1 (不是-0, 因為那會和第1個元素重合):

>>> greeting = ‘chongshi‘>>> greeting[-1]‘i‘>>> greeting[-2]‘h‘

 

當然,我們也可以通過另一種方式使用所引,兩種方式的效果是一樣的:

>>> ‘chongshi‘[0]‘c‘>>> ‘chongshi‘[-1]‘i‘

 

如果一個函數調用返回一個序列,那麼可以直接對返回結果進行索引操作。例如,假設只對使用者輸入年份的第4個數字感興趣,那麼,可以進行如下操作:

>>> fourth = raw_input(‘year:‘)[3]year:2013>>> fourth‘3‘

提示:請試著敲擊代碼,更能助幫你理解。不要懶得動手。

 

索引樣本:

#根據給定的年月日以數字形式列印出日期months = [    ‘January‘,    ‘February‘,    ‘March‘,    ‘April‘,    ‘May‘,    ‘June‘,    ‘July‘,    ‘August‘,    ‘September‘,    ‘October‘,    ‘November‘,    ‘December‘    ]#以1-31的數字作為結尾的列表endings = [‘st‘,‘nd‘,‘rd‘]+ 17*[‘th‘]           +[‘st‘,‘nd‘,‘rd‘]+ 7*[‘th‘]           +[‘st‘]year  =raw_input(‘year:‘)month =raw_input(‘month(1-12):‘)day   =raw_input(‘day(1-31)‘)month_number = int(month)day_number = int(day)#記得要將月份和天數減1,以獲得正確的索引month_name = months[month_number-1]ordinal = day + endings[day_number - 1]print month_name + ‘ ,‘ + ordinal + ‘ ,‘ + year-----------------------------------------------輸入:>>> year:2013month(1-12):4day(1-31)14輸出:April ,14th ,2013

 

分區

與使用索引來訪問單個元素類似,可以使用分區操作來訪問一琮範圍內的元素。分區通過冒號相隔的兩個索引來實現:

>>> tag = ‘<a href="http://www.python.org">Python web site</a>‘>>> tag[9:30]   # 取第9個到第30個之間的字元‘http://www.python.org‘>>> tag[32:-4]   #取第32到第-4(倒著數第4個字元)‘Python web site‘>>> 

 

如果求10個數最後三個數:

>>> numbers = [0,1,2,3,4,5,6,7,8,9]>>> numbers[7:-1]   # 從第7個數到 倒數第一個數[7, 8]              #顯然這樣不可行>>> numbers[7:10]   #從第7個數到第10個數[7, 8, 9]            #這樣可行,索引10指向的是第11個元素。>>> numbers[7:]    # 可以置空最後一個索引解決[7, 8, 9]>>> numbers[:3]   [0, 1, 2]>>> numbers[:][0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

 

分區樣本:

#  對http://fnng.cnblogs.com形式的URL進行分割url = raw_input(‘Please enter the URL:‘)domain = url[11:-4]print "Domain name:" + domain------------------------------------------
輸入:>>> Please enter the URL:http://fnng.cngblogs.com輸出:Domain name:.cngblogs

 

更大步長:

>>> numbers = [0,1,2,3,4,5,6,7,8,9]>>> numbers[0:10:1]   #求0到10之間的數,步長為1[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>>> numbers[0:10:2]   #步長為2[0, 2, 4, 6, 8]>>> numbers[0:10:3]   #步長為3[0, 3, 6, 9]

 

序列相加

通過使用加號可以進行序列的串連操作:

>>> ‘hello.‘+‘world!‘‘hello.world!‘>>> [1,2,3] + ‘world!‘Traceback (most recent call last):  File "<pyshell#20>", line 1, in <module>    [1,2,3] + ‘world!‘TypeError: can only concatenate list (not "str") to list

 

正如錯誤提示,列表和字串是無法串連接在一起的,儘管它他們都是序列。簡單來說,兩種相同類型的序列才能進行串連操作。

 

乘法

>>> ‘python ‘ * 5‘python python python python python ‘>>> [25] * 10[25, 25, 25, 25, 25, 25, 25, 25, 25, 25]

 

如果想建立一個佔用十個元素空間,卻不包括任何有用的內容的列表,可以用Nome

>>> sequence = [None] * 10>>> sequence[None, None, None, None, None, None, None, None, None, None]

 

序列(字串)乘法樣本:

# 以正確的寬度在置中的“盒子”內列印一個句子# 注意,整數除法運算子(//)只能用在python 2.2 以及後續版本,在之前的版本中,只能用普通除法(/)sentence = raw_input("Sentence : ")screen_width = 80text_width = len(sentence)box_width = text_width + 6left_margin = (screen_width - box_width) //2printprint ‘ ‘ * left_margin + ‘+‘ + ‘-‘ * (box_width - 2)+ ‘+‘print ‘ ‘ * left_margin + ‘|  ‘ + ‘ ‘ * text_width    + ‘  |‘print ‘ ‘ * left_margin + ‘|  ‘ +     sentence        + ‘  |‘print ‘ ‘ * left_margin + ‘|  ‘ + ‘ ‘ * text_width    + ‘  |‘print ‘ ‘ * left_margin + ‘+‘ + ‘-‘ * (box_width - 2)+ ‘+‘
---------------------------------------------------------
輸入:>>> Sentence : haha! this is my box輸出: +------------------------+ | | | haha! this is my box | | | +------------------------+

 

 

成員資格

 為了檢查一個值是否在序列中,可以使用in 運算子。該運算子和之前已經討論過的(例如 + , * 運算子)有一點不同。這個運算子檢查某個條件為真或假的(True or False )。

in運算子的例子:

>>> permissions = ‘rw‘>>> ‘w‘ in permissionsTrue>>> ‘y‘ in permissionsFalse>>> users = [‘zhangsan‘, ‘lisi‘,‘wangwu‘]>>> raw_input(‘Enter your user name: ‘) in usersEnter your user name: lisiTrue>>> subject =‘$$$ Get rich now!!! $$$‘>>> ‘$$$‘ in subjectTrue

 

長度、最小值和最大值 

內建函數len、min 和max 非常有用。Len函數返回序列中所包含元素的數量。Min函數和max函數則分別返回序列中最大和最小的元素。

>>> numbers = [100,34,678]>>> len (numbers)3>>> max(numbers)678>>> min(numbers)34>>> max(2,3)3>>> min(9,3,2,5)2

python基礎學習筆記(三)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.