Python 第二章-列表和元组
生活随笔
收集整理的這篇文章主要介紹了
Python 第二章-列表和元组
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
第二章-列表和元組
2.0? ? ??在Python中,最基本的數據結構是序列(sequence)。序列中的每個元素被分配一個序列號-即元素的位置,
也稱為索引。第一個索引是0,第二個是1,以此類推。
2.1 序列概覽
Python一共有6種內建的序列
{? ? 列表,元組,字符串,Unicode字符串,buffer對象和xrange對象
}
2.2通用序列操作
? ? 所有序列類型都可以進行某些特定的操作,這些操作包括:索引(indexing),分片(sliceing),加(adding),乘(multiplying)以及檢查某個元素是否屬于序列的成員(成員資格)。除此之外,Python還有計算序列長度,找出最大元素和最小的內建函數。? ?
>>>strA="abcdef"; >>>strA[0] 'a' >>>strA[-1] 'f' >>>'Hello'[1] 'e' >>> mark=input("aaaa:")[0] aaaa:55 >>> mark '5'? ??
? ??下面是輸入一個日期,整理后輸出(沒有什么特出月份的判斷啥的,就是為了理解語法)
代碼: ??
months=[ '1yue', '2yue', '3yue', '4yue', '5yue', '6yue', '7yue', '8yue', '9yue', '10yue', '11yue', '12yue', ]endings=['st','nd','rd'] + 17 *['th']\+['st','nd','rd'] + 7 *['th']\+['st']year = input("Year:") month = input("Month:(1-12)") day = input("Day:(1-31)")month_number = int(month) day_number = int(day) month_name=months[month_number-1] ordinal=day+endings[day_number-1] print(month_name + ' ' + ordinal + ' ' + year) input("Press<enter>") 運行結果: Year:1 Month:(1-12)2 Day:(1-31)3 2yue 3rd 1 Press<enter> <span style="font-size:18px;"><pre name="code" class="python"> <strong><span style="font-size:18px;">2.2.2分片(有點類似cmd里面的字符串處理)分片就是對字符串進行截取處理,這個截取是很靈活的,不解釋了,直接看例子吧。</span></span></strong> <strong><span style="font-size:18px;"> </span></strong>1.優雅地捷徑 >>> web='<a href="http://www.python.org">Python web site</a>' >>> web[9:3] '' >>> web[9:30] 'http://www.python.org' >>> web[32:-4] 'Python web site' >>> number=[1,2,3,4,5,6,7,8,9,10] >>> number[3:6] [4, 5, 6] >>> number[0:1] [1] >>> number[-3:-1] [8, 9] >>> number[-3:0] [] >>> number[-3:] [8, 9, 10] >>> number[3:] [4, 5, 6, 7, 8, 9, 10] >>> number[:3] [1, 2, 3] >>> number[:] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> print(number[:]) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> 2.更大的步長 - 分片 >>> number[0:10:1] [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> number[0:5:2] [1, 3, 5] >>> number[0:10:3] [1, 4, 7, 10] >>> number[3:6:3] [4] >>> number[::4] [1, 5, 9] >>> number[8:3:-1] [9, 8, 7, 6, 5] >>> number[3:8:1] [4, 5, 6, 7, 8] >>> number[10:0:-2] [10, 8, 6, 4, 2] >>> number[10:0] [] >>> number[10:0:-2] [10, 8, 6, 4, 2] >>> number[0:10:-2] [] >>> number[::-2] [10, 8, 6, 4, 2] >>> number[5::-2] [6, 4, 2] >>> number[5:] [6, 7, 8, 9, 10] >>> number[:5] [1, 2, 3, 4, 5] >>> number[:5:-2] [10, 8] >>> number[5::2] [6, 8, 10] >>> number[:5] [1, 2, 3, 4, 5]<strong><span style="font-size:18px;"> 在這里要得到正確的分片結果需要動些腦筋。開始的元素(最左邊元素)包括在結果之中,而結束點的元素(最右邊的元素)則不在分片之內。當使用一個負數作為步長時,必須讓開始點 大于結束點。在沒有明確指定開始點和結束點的時候,正負數的使用可能會帶來一些混淆。不過在這種情況下Python會進行正確的操作:對于一個正數步長,Python會從序列的頭部開始向右提取 元素,直到最后一個元素;而對于負數步長,則是從序列的尾部開始向左提取元素,直到第一個元素。</span><span style="font-size:18px;">2.2.3 序列相加通過使用加號可以進行序列的連接操作</span></strong> >>> [1,2,3]+[4,5,6] [1, 2, 3, 4, 5, 6] >>> 'Hellow' + 'World!' 'HellowWorld!' >>> [1,2,3]+'world' Traceback (most recent call last):File "<pyshell#2>", line 1, in <module> [1,2,3]+'world' TypeError: can only concatenate list (not "str") to list<strong><span style="font-size:18px;">2.2.4乘法</span></strong> >>> 'asd'*5 'asdasdasdasdasd' >>> [15]*5 [15, 15, 15, 15, 15] >>> sequence=[None]*10 >>> sequence [None, None, None, None, None, None, None, None, None, None]<strong><span style="font-size:18px;">例子:打印一個盒子,然后在里面打印一行字</span></strong>sentence=input("sentence:") screen_whdth=80 text_width=len(sentence) box_width= text_width - 6 left_margin = (screen_whdth - box_width) // 2 print() print(' ' * 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) + '+') print() <strong><span style="font-size:18px;">ps:效果特別不好,書上沒算準,懶得去改了,就是想熟悉下語法,實現結果不重要</span> <span style="font-size:18px;"> 2.2.5成員資格(in 判斷成員是不是在序列中)</span></strong> permissions='rw' 'w' in permissions 'x' in permissions users=['mlh' ,'foo' ,'bar'] input('enter your user name:') in users subjuce='aada Get rich now!!! aada' 'aaa' in subjuce<strong><span style="font-size:18px;">例子#檢查用戶名和PIN碼 代碼 </span></strong> database = [['albert' ,'1234'],['sdfddd' ,'2345'],['sdsddd' ,'4567'],['sdasaw' ,'8658'], ] username = input('User Name:') pin = input('Pin code: ') if([username,pin] in database): print("ok") else: print("no");結果 >>> User Name:albert Pin code: 1234 ok >>> <strong><span style="font-size:18px;">2.2.6 列表的長度、最小值和最大值</span></strong> numbers = [100,34,678] len(numbers) max(numbers) min(numbers) max(2,3); min(9,3,2,5)<strong><span style="font-size:18px;">2.3 列表:Python的"苦力" 列表不同于元組和字符串,列表本身是可以修改的,同時有它專門的好用的方法。2.3.1 list函數 字符串創建列表</span></strong> >>> list("Hello") ['H', 'e', 'l', 'l', 'o'] >>> aa = list("Hello") >>> aa*3 ['H', 'e', 'l', 'l', 'o', 'H', 'e', 'l', 'l', 'o', 'H', 'e', 'l', 'l', 'o'] >>> <strong><span style="font-size:18px;">2.3.2 基本的列表操作</span><span style="font-size:18px;">1.列表是可修改的</span></strong> x=[1,1,1] x[1] = 2 print(x) [1, 2, 1]<strong><span style="font-size:18px;">2.刪除元素</span></strong> [1, 2, 1] >>> name = ['1' ,'2' ,'3'] >>> name ['1', '2', '3'] >>> del name[1] >>> name ['1', '3'] >>> <strong><span style="font-size:18px;">3.分片賦值 例子</span></strong> name=list('Perl') print(name) name[2:]=list('ar') print(name) 結果>>> ['P', 'e', 'r', 'l'] ['P', 'e', 'a', 'r'] >>> <strong><span style="font-size:18px;">4.不等長替換</span></strong> name=list('Perl'); name[1:] = list("ython"); print(name);<strong><span style="font-size:18px;">5.插入元素</span></strong> numbers=[1,5]; numbers[1:1] = [2,3,4]; print(numbers);<strong><span style="font-size:18px;">6通過替換刪除片段</span></strong> numbers[1:4] = []; print(numbers);<strong><span style="font-size:18px;">7.del刪除片段</span></strong> numbers = [1,2,3,4,5]; del numbers[1:2]; print(numbers);<strong><span style="font-size:18px;">2.3.3 列表方法 #1.append 在列表末端追加新對象</span></strong> lst = [1,2,3] lst.append(4) print(lst)#2.count 方法統計某個元素在列表中出現的次數 print(['to','be','or','not','to','be'].count('to')); x = [[1,2],1,1,[2,1,[1,2]]] print(x.count(1)); print(x.count([1,2]));#3.extend方法可以在列表末尾一次性追加另一個序列中的多個值,用一個列表擴充另一個列表 a = [1 ,2 ,3]; b = [4 ,5 ,6]; a.extend(b); print(a); <strong><span style="font-size:18px;">#ps: a=a+b 的效率比a.extend(b)低,這個不解釋了,很好理解,a=a+b要創建副本#4.index 從列表中找出某個第一次匹配項的索引位置</span></strong> knights = ['we' ,'are' ,'the' ,'knights' ,'who' ,'say' ,'ni']; x = knights.index('who'); print(x); x = knights.index('ss'); print(x); 輸出: 4 Traceback (most recent call last):File "C:/Users/King/Desktop/s.py", line 5, in <module> x = knights.index('ss'); ValueError: 'ss' is not in list >>> <strong><span style="font-size:18px;">ps:找不到就異常了,額...感覺不是很科學 #5.insert 方法用于將對象插入到列表中</span></strong> >>> numbers = [1,2,3,4,5,6,7] >>> numbers.insert(3,'four') >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> #等價于 >>> numbers = [1,2,3,4,5,6,7] >>> numbers[3:3] = ['four'] >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> #但是沒有insert直觀 >>> <strong><span style="font-size:18px;">#6.pop 從列表尾部取出一個值 出棧 #Python里 列表+append+pop 可以模擬出來一個棧</span></strong> x = [1 ,2, 3] x.append(x.pop()) print(x) [1,2,3] <strong><span style="font-size:18px;">#ps: 如果想模擬隊列就用 inset(0,...) pop(0)#7.remove 方法用于溢出列表中某個值得第一個匹配項</span></strong> x = ['to' ,'be' ,'or' ,'not' ,'to' ,'be']; x.remove('be'); print(x); x.remove('bee'); <strong><span style="font-size:18px;">#移除不存在的依然報錯#8.reverse 方法將列表中的元素反向存放</span></strong> x = [1,2,3]; x.reverse(); print(x); <strong><span style="font-size:18px;">#ps 如果需要對一個序列進行反向迭代,那么可以使用reversed函數,這個函數并不會返回 #一個列表,而是返回一個迭代器(iterator)對象,盡管如此,使用list函數把返回的對象 #轉換成列表也是可行的:</span></strong> x = [1 ,2 ,3]; print(list(reversed(x)));<strong><span style="font-size:18px;">#9.sort排序</span></strong> 1. >>> x = [5 ,4 ,3 ,2 ,1] >>> y = x >>> x.sort() >>> x [1, 2, 3, 4, 5] >>> y [1, 2, 3, 4, 5] >>> 2. >>> x = [3 ,2 ,1] >>> y = x[:] >>> x.sort() >>> x [1, 2, 3] >>> y [3, 2, 1] >>> <strong><span style="font-size:18px;">3.sorted函數</span></strong> >>> x = [5 ,4 ,3 ,2 ,1] >>> y = sorted(x) >>> x [5, 4, 3, 2, 1] >>> y [1, 2, 3, 4, 5] >>> <strong><span style="font-size:18px;">4.從大到小</span></strong> >>> x = [5 ,2 ,3 ,4] >>> x.sort() >>> x.reverse() >>> x [5, 4, 3, 2] >>> <strong><span style="font-size:18px;">ps:也可以 sorted(x).reverse() ,但是x.sort().reverse()不行,因為x.sort()返回None,不能排序#10.高級排序 1.首先,類似于c++里面的那個sort函數支持的cmp一樣,這個也支持</span></strong>numbers = [5 ,2 ,9 ,7];numbers.sort(cmp);numbers[2 ,5 ,9 ,7]<strong><span style="font-size:18px;">ps:前提是定義好cmp函數,不然運行出錯,這個后面說</span></strong> <strong><span style="font-size:18px;">2.還有兩個可選參數 key和reverse 一個是排序依據(key有點cmp的意思),另一個是方向</span></strong> >>> x = ['111' ,'23213' ,'3'] >>> x.sort(key=len) >>> x ['3', '111', '23213'] >>> x.sort() >>> x ['111', '23213', '3'] >>> x.sort(reverse=True) >>> x ['3', '23213', '111'] >>> <strong><span style="font-size:18px;"> 2.4元組是不能改變的列表,單個后面必須有,而且通常()包起來</span></strong> >>> 1,2,3 (1, 2, 3) >>> (1,2,3) (1, 2, 3) >>> () () >>> ()*10 () >>> (1,)*10 (1, 1, 1, 1, 1, 1, 1, 1, 1, 1) >>> 3*(40+2) 126 >>> 3*(40+2,) (42, 42, 42) >>> 2.4.1 tuple函數,把序列轉成元組>>> tuple([1,2,3]) (1, 2, 3) >>> tuple((1,2,3)) (1, 2, 3) >>> <strong><span style="font-size:18px;">2.4.2 元組的基本操作元組本身并不復雜,除了創建和訪問之外沒啥別的</span></strong> >>> x = 1,2,3 >>> x (1, 2, 3) >>> y=(1,2,3); >>> y[0:2] (1, 2) >>>
2.4.3 那么,元組到底有卵用?
1.元組可以在映射(和集合的成員)中當做鍵使用-而列表不行。2.元組作為很多內建函數的返回值存在,也就是說必須對元組進行處理,只要不嘗試修改元組,那么"處理"元組在絕大多數情況下就是把他們當做列表進行操作。一般來說,列表肯能更能滿足對序列的所有需求。
?ps:
? ? ? ? ?我X,看了這兩個不是理由的理由,真是覺得元組本身沒什么卵用。只是沒辦法才使用,本來以為只讀的有什么高效的地方。
????
?
總結
以上是生活随笔為你收集整理的Python 第二章-列表和元组的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python第一章-基础知识
- 下一篇: Python第三章-字符串