標籤:元組的使用
一、元組的值不能被修改
#!/usr/bin/pythontup =("a","b","c");tup[1]=7
執行後出現如下錯誤:
Traceback (most recent call last):
File "C:\Program Files\Sublime Text 3\time.py", line 4, in <module>
tup[1]=7
TypeError: ‘tuple‘ object does not support item assignment
二、元組的元素不能單個刪除,只能全部刪除
#!/usr/bin/pythontup =("a","b","c");del tupprint "After deleting tuple:\n"print tup
執行結果:
After deleting tuple:
Traceback (most recent call last):
File "C:\Program Files\Sublime Text 3\time.py", line 6, in <module>
print tup
NameError: name ‘tup‘ is not defined
三、只有一個元素的元組圓括弧必須有逗號,否則不會認為是元組
#!/usr/bin/pythontupleone=(1,)print "tupleone is :",type(tupleone)tupleoneerror=(1)print "tupleanotherone is :",type(tupleoneerror)
執行結果;
tupleone is : <type ‘tuple‘>
tupleanotherone is : <type ‘int‘>
四、元組元素的拆分,定義變數
#!/usr/bin/pythonmyinfo=("jinhoward",30,"Male")name,age,gender=myinfoprint "Name=",nameprint "Age=",ageprint "Gender=",gender
執行結果:
Name= jinhoward
Age= 30
Gender= Male
Python學習第二篇之tuple