講述Python序列如何進行解包教程
Python序列具有很廣泛的應用范圍,在實際的應用中還是有不少的問題需要我們大家解決。下面我們就來看看相關的問題如何進行解決。希望在今后的工作中有所幫助。#t#
Python序列(字符串,列表,元組)
Python序列的***個元素從0開始,它不但可以從頭開始訪問,也可以從尾部訪問,***一個元素是a[-1],倒數第二個是a[-2],倒數第i個是a[-i].
列表的創建,遍歷,修改等,列表中可以存儲不同類型的元素,習慣上都使用列表存儲通類型的數據。長度可以在運行時修改。
元組,通常存儲異種數據的序列,這個也是習慣,非規則。長度事先確定的,不可以在程序執行期間更改。元組的創建可以訪問:
- 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)來創建元組,稱為”元組打包”,因為值被“打包到元組中”,元組和其他序列可以“解包”即將序列中存儲的值指派給各個標識符。例子:
# 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 )
以上就是對Python序列的相關介紹。希望對大家有所幫助。