Python內建資料結構
在這篇文章中,我們將學習Python中的4種內建資料結構:列表、字典、元組和集合。
列表
列表是有序的元素序列。它是一種非標量資料結構,並且是可變的。與儲存相同資料型別元素的陣列不同,列表可以包含不同資料型別。
可以透過在方括號中包含索引來訪問列表。
現在讓我們看一個例子來更好地理解列表。
示例
lis=['tutorialspoint',786,34.56,2+3j]
# displaying element of list
for i in lis:
print(i)
# adding an elements at end of list
lis.append('python')
#displaying the length of the list
print("length os list is:",len(lis))
# removing an element from the list
lis.pop()
print(lis)輸出
tutorialspoint 786 34.56 (2+3j) length os list is: 5 ['tutorialspoint', 786, 34.56, (2+3j)]
元組
它也是在Python中定義的非標量型別。與列表一樣,它也是有序的字元序列,但元組本質上是不可變的。這意味著不允許對這種資料結構進行任何修改。
元素可以是異構或同構的,用逗號分隔,括在括號內。
讓我們來看一個例子。
示例
tup=('tutorialspoint',786,34.56,2+3j)
# displaying element of list
for i in tup:
print(i)
# adding elements at the end of the tuple will give an error
# tup.append('python')
# displaying the length of the list
print("length os tuple is:",len(tup))
# removing an element from the tup will give an error
# tup.pop()輸出
tutorialspoint 786 34.56 (2+3j) length os tuple is: 4
集合
它是一個無序的物件集合,不包含任何重複項。這可以透過將所有元素括在花括號中來完成。我們也可以使用關鍵字“set”透過型別轉換來形成集合。
集合的元素必須是不可變資料型別。集合不支援索引、切片、連線和複製。我們可以使用索引迭代元素。
現在讓我們來看一個例子。
示例
set_={'tutorial','point','python'}
for i in set_:
print(i,end=" ")
# print the maximum and minimum
print(max(set_))
print(min(set_))
# print the length of set
print(len(set_))輸出
tutorial point python tutorial point 3
字典
字典是鍵值對的無序序列。索引可以是任何不可變型別,稱為鍵。這也用花括號指定。
我們可以透過與其關聯的唯一鍵來訪問值。
讓我們來看一個例子。
示例
# Create a new dictionary d = dict() # Add a key - value pairs to dictionary d['tutorial'] = 786 d['point'] = 56 # print the min and max print (min(d),max(d)) # print only the keys print (d.keys()) # print only values print (d.values())
輸出
point tutorial dict_keys(['tutorial', 'point']) dict_values([786, 56])
結論
在這篇文章中,我們學習了Python語言中存在的內建資料結構及其實現。
廣告
資料結構
網路
關係資料庫管理系統(RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP