python 資料結構 元組 tuple

2021-08-29 18:02:40 字數 1962 閱讀 2224

字串

>>>#變數引用str

>>> s = "abc"

>>> s

'abc'

元組
>>>#如果這樣寫,就會是...

>>> t = 123,'abc',["come","here"]

>>> t

(123, 'abc', ['come', 'here'])

上面例子中看到的變數t,並沒有報錯,也沒有「最後乙個有效」,而是將物件做為乙個新的資料型別:tuple(元組),賦值給了變數t。

元組是用圓括號括起來的,其中的元素之間用逗號隔開。(都是英文半形)

tuple是一種序列型別的資料,這點上跟list/str類似。它的特點就是其中的元素不能更改,這點上跟list不同,倒是跟str類似;它的元素又可以是任何型別的資料,這點上跟list相同,但不同於str。

>>> t = 1,"23",[123,"abc"],("python","learn")   #元素多樣性,近list

>>> t

(1, '23', [123, 'abc'], ('python', 'learn'))

>>> t[0] = 8  #不能原地修改,近str

traceback (most recent call last):

file "", line 1, in typeerror: 'tuple' object does not support item assignment

traceback (most recent call last):

>>>

從上面的簡單比較似乎可以認為,tuple就是乙個融合了部分list和部分str屬性的雜交產物。此言有理。

>>> one_list = ["python","hiekay","github","io"]

>>> one_list[2]

'github'

>>> one_list[1:]

['hiekay', 'github', 'io']

>>> for word in one_list:

... print word

...python

hiekay

github

io>>> len(one_list)

4

>>> t

(1, '23', [123, 'abc'], ('python', 'learn'))

>>> t[2]

[123, 'abc']

>>> t[1:]

('23', [123, 'abc'], ('python', 'learn'))

>>> for every in t:

... print every

...1

23[123, 'abc']

('python', 'learn')

>>> len(t)

4>>> t[2][0] #還能這樣呀,哦對了,list中也能這樣

123>>> t[3][1]

'learn'

>>> t

(1, '23', [123, 'abc'], ('python', 'learn'))

>>> tls = list(t) #tuple-->list

>>> tls

[1, '23', [123, 'abc'], ('python', 'learn')]

>>> t_tuple = tuple(tls) #list-->tuple

>>> t_tuple

(1, '23', [123, 'abc'], ('python', 'learn'))

Python之資料結構 元組

元組與列表的最大區別是列表可以修改 可以讀取 可以刪除,而元組建立之後則不能修改,但是可以刪除整個元組。1 定義元組 l1 1,2,3 print l1 print type l1 執行結果 如果元組只有乙個元素,則這個元素後面必須要有 否則元素就還是其原來的型別。l1 1,2,3 print l1...

Python的資料結構 元組

zoo 大象 老虎 獅子 北極熊 print the animal number of the is len zoo print the animal of the zoo are zoo new zoo 孔雀 鱷魚 zoo print the new animal is new zoo print...

Python中的資料結構 元組

元組是既定的,決定於建立的時候,所以不存在增刪改等一些操作。1.可變型別 2.不可變型別 a 1a 2 b 1print id 1 print id a print id b a和b都指向1的時候其位址相同,當a指向2的時候,a的位址變了,但是1本身是不變的 建立乙個元組 t 1,2,oop 4,2...