Python中有3中內建的資料結構——列表、元組和字典。
1. 列表(List)
列表用一對方括弧[]表示,每項資料之間用逗號隔開。一旦你建立了一個列表,你可以對它進行添加、刪除或搜尋。所以列表是可以改變的。
1)建立列表
shoplist = ["apple", "mango", "carrot", "banana"]print("I have", len(shoplist), "items to purchase.")
2)遍曆
for item in shoplist: print(item)
3)添加資料
print("I also have to buy rice.")shoplist.append("rice")print("My shopping list is now", shoplist)
4)排序
shoplist.sort()print("Sorted shopping list is", shoplist)
5)檢索
print("The first item I will buy is", shoplist[0])
6)刪除資料
olditem = shoplist[0]del shoplist[0]print("I bought the", olditem)print("My shopping list is now", shoplist)
2. 元組
元組和列表十分類似,只不過元組是不可以改變的,即不能被修改。元組是用一對圓括弧()表示,每項資料之間也是用逗號隔開。元組通常用在使語句或使用者定義的函數能夠安全地採用一組值的時候,即被使用的元組的值不會改變。
zoo = ("wolf", "elephant", "penguin")print("Number of animals in the zoo is", len(zoo))new_zoo = ("monkey", "dolphin", zoo)print("Number of animals in the new zoo is", len(new_zoo))print("All animals in new zoo are", new_zoo)print("Animals brought from old zoo are", new_zoo[2])print("Last animal brought from old zoo is", new_zoo[2][2])
元組有與列表一樣的索引運算子。含有0個或1個項目的元組。一個空的元組由一對空的圓括弧組成,如myempty = ()。然而,含有單個元素的元組就不那麼簡單了。你必須在第一個(唯一一個)項目後跟一個逗號,這樣Python才能區分元組和運算式中一個帶圓括弧的對象。即如果你想要的是一個包含項目2的元組的時候,你應該指明singleton = (2 , )。
元組最通常的用法是用在列印語句中。
age = 22name = "Swaroop"print("%s is %d years old" % (name, age))print("Why is %s playing with that python?" % name)
%s表示字串,%d表示整數。
3. 字典(dict)
字典是一個索引值對集合,鍵必須是唯一的。注意,你只能使用不可變的對象(比如字串)來作為字典的鍵,但是你可以把不可變或可變的對象作為字典的值。字典是用一對花括弧{}表示,每個索引值對之間用逗號隔開,索引值之間用冒號分隔。
1)建立字典
ab = {"user1" : "user1@test.com", "user2" : "user2@test.com"}
2)遍曆
for name, address in ab.items(): print("Contact %s at %s" % (name, address))
3)添加資料
if not "tom" in ab:#OR not ab.has_key("tom") ab["Tom"] = "tom@test.com"
4)檢索
print("user1's address is %s" % ab["user1"])
5)刪除
del ab["tom"]
4. 序列
列表、元組和字串都是序列,序列的兩個主要特點是索引操作符和切片操作符。索引操作符讓我們可以從序列中抓取一個特定項目。切片操作符讓我們能夠擷取序列的一個切片,即一部分序列。
#Indexing or "Subscription" operationprint("Item 0 is", shoplist[0])print("Item -1 is", shoplist[-1])#Slicing on a listprint("Item 1 to 3 is", shoplist[1:3])print("Item 2 to end is", shoplist[2:])print("Item 1 to -1 is", shoplist[1:-1])print("Item start to end is", shoplist[:])#Slicing on a stringname = "known"print("charactor 1 to 3 is", name[1:3])
索引同樣可以是負數,在那樣的情況下,位置是從序列尾開始計算的。因此,shoplist[-1]表示序列的最後一個元素而shoplist[-2]抓取序列的倒數第二個項目。
切片操作符是序列名後跟一個方括弧,方括弧中有一對可選的數字,並用冒號分割。注意這與你使用的索引操作符十分相似。記住數是可選的,而冒號是必須的。
切片操作符中的第一個數(冒號之前)表示切片開始的位置,第二個數(冒號之後)表示切片到哪裡結束。如果不指定第一個數,Python就從序列首開始。如果沒有指定第二個數,則Python會停止在序列尾。注意,返回的序列從開始位置 開始 ,剛好在 結束 位置之前結束。即開始位置是包含在序列切片中的,而結束位置被排斥在切片外。
5. 對象與引用
print("Simple Assignment")shoplist = ['apple', 'mango', 'carrot', 'banana']mylist = shoplist # mylist is just another name pointing to the same object!del shoplist[0]print("shoplist is", shoplist)print("mylist is", mylist)# notice that both shoplist and mylist both print the same list without# the 'apple' confirming that they point to the same objectprint("Copy by making a full slice")mylist = shoplist[:] # make a copy by doing a full slicedel mylist[0] # remove first itemprint("shoplist is", shoplist)print("mylist is", mylist)# notice that now the two lists are different
輸出結果:
Simple Assignment
shoplist is ["mango", "carrot", "banana"]
mylist is ["mango", "carrot", "banana"]
Copy by making a full slice
shoplist is ["mango", "carrot", "banana"]
mylist is ["carrot", "banana"]
6. 字串函數
name = "Swaroop" # This is a string objectif name.startswith("Swa"): print("Yes, the string starts with 'Swa'")if "a" in name: print("Yes, it contains the string 'a'")if name.find("war") != -1: print("Yes, it contains the string 'war'")delimiter = "_*_"mylist = ["Brazil", "Russia", "India", "China"]print(delimiter.join(mylist))
輸出結果:
Yes, the string starts with 'Swa'
Yes, it contains the string 'a'
Yes, it contains the string 'war'
Brazil_*_Russia_*_India_*_China