當(dāng)前位置:
首頁(yè) >
Python 第二章-列表和元组
發(fā)布時(shí)間:2025/6/17
40
豆豆
生活随笔
收集整理的這篇文章主要介紹了
Python 第二章-列表和元组
小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
第二章-列表和元組
2.0? ? ??在Python中,最基本的數(shù)據(jù)結(jié)構(gòu)是序列(sequence)。序列中的每個(gè)元素被分配一個(gè)序列號(hào)-即元素的位置,
也稱為索引。第一個(gè)索引是0,第二個(gè)是1,以此類推。
2.1 序列概覽
Python一共有6種內(nèi)建的序列
{? ? 列表,元組,字符串,Unicode字符串,buffer對(duì)象和xrange對(duì)象
}
2.2通用序列操作
? ? 所有序列類型都可以進(jìn)行某些特定的操作,這些操作包括:索引(indexing),分片(sliceing),加(adding),乘(multiplying)以及檢查某個(gè)元素是否屬于序列的成員(成員資格)。除此之外,Python還有計(jì)算序列長(zhǎng)度,找出最大元素和最小的內(nèi)建函數(shù)。? ?
>>>strA="abcdef"; >>>strA[0] 'a' >>>strA[-1] 'f' >>>'Hello'[1] 'e' >>> mark=input("aaaa:")[0] aaaa:55 >>> mark '5'? ??
? ??下面是輸入一個(gè)日期,整理后輸出(沒(méi)有什么特出月份的判斷啥的,就是為了理解語(yǔ)法)
代碼: ??
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>") 運(yùn)行結(jié)果: 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分片(有點(diǎn)類似cmd里面的字符串處理)分片就是對(duì)字符串進(jìn)行截取處理,這個(gè)截取是很靈活的,不解釋了,直接看例子吧。</span></span></strong> <strong><span style="font-size:18px;"> </span></strong>1.優(yōu)雅地捷徑 >>> 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.更大的步長(zhǎng) - 分片 >>> 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;"> 在這里要得到正確的分片結(jié)果需要?jiǎng)有┠X筋。開(kāi)始的元素(最左邊元素)包括在結(jié)果之中,而結(jié)束點(diǎn)的元素(最右邊的元素)則不在分片之內(nèi)。當(dāng)使用一個(gè)負(fù)數(shù)作為步長(zhǎng)時(shí),必須讓開(kāi)始點(diǎn) 大于結(jié)束點(diǎn)。在沒(méi)有明確指定開(kāi)始點(diǎn)和結(jié)束點(diǎn)的時(shí)候,正負(fù)數(shù)的使用可能會(huì)帶來(lái)一些混淆。不過(guò)在這種情況下Python會(huì)進(jìn)行正確的操作:對(duì)于一個(gè)正數(shù)步長(zhǎng),Python會(huì)從序列的頭部開(kāi)始向右提取 元素,直到最后一個(gè)元素;而對(duì)于負(fù)數(shù)步長(zhǎng),則是從序列的尾部開(kāi)始向左提取元素,直到第一個(gè)元素。</span><span style="font-size:18px;">2.2.3 序列相加通過(guò)使用加號(hào)可以進(jìn)行序列的連接操作</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;">例子:打印一個(gè)盒子,然后在里面打印一行字</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:效果特別不好,書(shū)上沒(méi)算準(zhǔn),懶得去改了,就是想熟悉下語(yǔ)法,實(shí)現(xiàn)結(jié)果不重要</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");結(jié)果 >>> User Name:albert Pin code: 1234 ok >>> <strong><span style="font-size:18px;">2.2.6 列表的長(zhǎng)度、最小值和最大值</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的"苦力" 列表不同于元組和字符串,列表本身是可以修改的,同時(shí)有它專門(mén)的好用的方法。2.3.1 list函數(shù) 字符串創(chuàng)建列表</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) 結(jié)果>>> ['P', 'e', 'r', 'l'] ['P', 'e', 'a', 'r'] >>> <strong><span style="font-size:18px;">4.不等長(zhǎng)替換</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通過(guò)替換刪除片段</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 在列表末端追加新對(duì)象</span></strong> lst = [1,2,3] lst.append(4) print(lst)#2.count 方法統(tǒng)計(jì)某個(gè)元素在列表中出現(xiàn)的次數(shù) 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方法可以在列表末尾一次性追加另一個(gè)序列中的多個(gè)值,用一個(gè)列表擴(kuò)充另一個(gè)列表 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)低,這個(gè)不解釋了,很好理解,a=a+b要?jiǎng)?chuàng)建副本#4.index 從列表中找出某個(gè)第一次匹配項(xiàng)的索引位置</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:找不到就異常了,額...感覺(jué)不是很科學(xué) #5.insert 方法用于將對(duì)象插入到列表中</span></strong> >>> numbers = [1,2,3,4,5,6,7] >>> numbers.insert(3,'four') >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> #等價(jià)于 >>> numbers = [1,2,3,4,5,6,7] >>> numbers[3:3] = ['four'] >>> numbers [1, 2, 3, 'four', 4, 5, 6, 7] >>> #但是沒(méi)有insert直觀 >>> <strong><span style="font-size:18px;">#6.pop 從列表尾部取出一個(gè)值 出棧 #Python里 列表+append+pop 可以模擬出來(lái)一個(gè)棧</span></strong> x = [1 ,2, 3] x.append(x.pop()) print(x) [1,2,3] <strong><span style="font-size:18px;">#ps: 如果想模擬隊(duì)列就用 inset(0,...) pop(0)#7.remove 方法用于溢出列表中某個(gè)值得第一個(gè)匹配項(xiàng)</span></strong> x = ['to' ,'be' ,'or' ,'not' ,'to' ,'be']; x.remove('be'); print(x); x.remove('bee'); <strong><span style="font-size:18px;">#移除不存在的依然報(bào)錯(cuò)#8.reverse 方法將列表中的元素反向存放</span></strong> x = [1,2,3]; x.reverse(); print(x); <strong><span style="font-size:18px;">#ps 如果需要對(duì)一個(gè)序列進(jìn)行反向迭代,那么可以使用reversed函數(shù),這個(gè)函數(shù)并不會(huì)返回 #一個(gè)列表,而是返回一個(gè)迭代器(iterator)對(duì)象,盡管如此,使用list函數(shù)把返回的對(duì)象 #轉(zhuǎn)換成列表也是可行的:</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函數(shù)</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()不行,因?yàn)閤.sort()返回None,不能排序#10.高級(jí)排序 1.首先,類似于c++里面的那個(gè)sort函數(shù)支持的cmp一樣,這個(gè)也支持</span></strong>numbers = [5 ,2 ,9 ,7];numbers.sort(cmp);numbers[2 ,5 ,9 ,7]<strong><span style="font-size:18px;">ps:前提是定義好cmp函數(shù),不然運(yùn)行出錯(cuò),這個(gè)后面說(shuō)</span></strong> <strong><span style="font-size:18px;">2.還有兩個(gè)可選參數(shù) key和reverse 一個(gè)是排序依據(jù)(key有點(diǎn)cmp的意思),另一個(gè)是方向</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元組是不能改變的列表,單個(gè)后面必須有,而且通常()包起來(lái)</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函數(shù),把序列轉(zhuǎn)成元組>>> tuple([1,2,3]) (1, 2, 3) >>> tuple((1,2,3)) (1, 2, 3) >>> <strong><span style="font-size:18px;">2.4.2 元組的基本操作元組本身并不復(fù)雜,除了創(chuàng)建和訪問(wèn)之外沒(méi)啥別的</span></strong> >>> x = 1,2,3 >>> x (1, 2, 3) >>> y=(1,2,3); >>> y[0:2] (1, 2) >>>
2.4.3 那么,元組到底有卵用?
1.元組可以在映射(和集合的成員)中當(dāng)做鍵使用-而列表不行。2.元組作為很多內(nèi)建函數(shù)的返回值存在,也就是說(shuō)必須對(duì)元組進(jìn)行處理,只要不嘗試修改元組,那么"處理"元組在絕大多數(shù)情況下就是把他們當(dāng)做列表進(jìn)行操作。一般來(lái)說(shuō),列表肯能更能滿足對(duì)序列的所有需求。
?ps:
? ? ? ? ?我X,看了這兩個(gè)不是理由的理由,真是覺(jué)得元組本身沒(méi)什么卵用。只是沒(méi)辦法才使用,本來(lái)以為只讀的有什么高效的地方。
????
?
總結(jié)
以上是生活随笔為你收集整理的Python 第二章-列表和元组的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: Python第一章-基础知识
- 下一篇: Python第三章-字符串