python的userlist_Python Collections.UserList用法及代码示例

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值