講述Python序列如何進(jìn)行解包教程
Python序列具有很廣泛的應(yīng)用范圍,在實(shí)際的應(yīng)用中還是有不少的問(wèn)題需要我們大家解決。下面我們就來(lái)看看相關(guān)的問(wèn)題如何進(jìn)行解決。希望在今后的工作中有所幫助。#t#
Python序列(字符串,列表,元組)
Python序列的***個(gè)元素從0開(kāi)始,它不但可以從頭開(kāi)始訪問(wèn),也可以從尾部訪問(wèn),***一個(gè)元素是a[-1],倒數(shù)第二個(gè)是a[-2],倒數(shù)第i個(gè)是a[-i].
列表的創(chuàng)建,遍歷,修改等,列表中可以存儲(chǔ)不同類型的元素,習(xí)慣上都使用列表存儲(chǔ)通類型的數(shù)據(jù)。長(zhǎng)度可以在運(yùn)行時(shí)修改。
元組,通常存儲(chǔ)異種數(shù)據(jù)的序列,這個(gè)也是習(xí)慣,非規(guī)則。長(zhǎng)度事先確定的,不可以在程序執(zhí)行期間更改。元組的創(chuàng)建可以訪問(wèn):
- aList = []for number in range( 1, 11 ): aList += [ number ]
print "The value of aList is:", aList for item in aList: print item,
print for i in range( len( aList ) ): print "%9d %7d" %
( i, aList[ i ] )aList[ 0 ] = -100 aList[ -3 ] = 19print "Value of aList after modification:", aList- 7.3.
- hour = 2
- minute = 12
- second = 34
- currentTime = hour, minute, second # create tuple
- print "The value of currentTime is:", currentTime
Python序列解包
atupe=(1,2,3)來(lái)創(chuàng)建元組,稱為”元組打包”,因?yàn)橹当?ldquo;打包到元組中”,元組和其他序列可以“解包”即將序列中存儲(chǔ)的值指派給各個(gè)標(biāo)識(shí)符。例子:
# create sequencesaString = "abc"aList = [ 1, 2, 3 ]
aTuple = "a", "A",- # unpack sequences to variablesprint "Unpacking string..."
first, second, third = aStringprint "String values:", first,
second, third print "\nUnpacking list..."first, second,
third = aListprint "List values:", first, second, third
print "\nUnpacking tuple..."first, second, third = aTupleprint
"Tuple values:", first, second, third- # swapping two valuesx = 3y = 4 print "\nBefore
swapping: x = %d, y = %d" % ( x, y )x, yy = y, x # swap varia
blesprint "After swapping: x = %d, y = %d" % ( x, y )
以上就是對(duì)Python序列的相關(guān)介紹。希望對(duì)大家有所幫助。