Python列表是array-like數據結構,但與之不同的是它是同質的。單個列表可能包含數據類型,例如整數,字符串以及對象。 Python中的列表是有序的,并且有一定數量。根據確定的序列對列表中的元素進行索引,并使用0作為第一個索引來完成列表的索引。
注意:有關更多信息,請參閱Python列表。
Collections.UserList
Python支持一個List,如collections模塊中存在的名為UserList的容器。此類用作List對象的包裝器類。當一個人想要創建自己的具有某些修改功能或某些新功能的列表時,此類非常有用。它可以被視為為列表添加新行為的一種方式。此類將列表實例作為參數,并模擬保存在常規列表中的列表。該列表可通過此類的data屬性訪問。
用法:
collections.UserList([list])
范例1:
# Python program to demonstrate
# userlist
from collections import UserList
L = [1, 2, 3, 4]
# Creating a userlist
userL = UserList(L)
print(userL.data)
# Creating empty userlist
userL = UserList()
print(userL.data)
輸出:
[1, 2, 3, 4]
[]
范例2:
# Python program to demonstrate
# userlist
from collections import UserList
# Creating a List where
# deletion is not allowed
class MyList(UserList):
# Function to stop deleltion
# from List
def remove(self, s = None):
raise RuntimeError("Deletion not allowed")
# Function to stop pop from
# List
def pop(self, s = None):
raise RuntimeError("Deletion not allowed")
# Driver's code
L = MyList([1, 2, 3, 4])
print("Original List")
# Inserting to List"
L.append(5)
print("After Insertion")
print(L)
# Deliting From List
L.remove()
輸出:
Original List
After Insertion
[1, 2, 3, 4, 5]
Traceback (most recent call last):
File "/home/9399c9e865a7493dce58e88571472d23.py", line 33, in L.remove()
File "/home/9399c9e865a7493dce58e88571472d23.py", line 15, in remove
raise RuntimeError("Deletion not allowed")
RuntimeError:Deletion not allowed