python如何创建一个列表_如何基于另一个列表创建Python列表

您可以使用子类化列表的自定义类.这样,您可以调整.remove的行为:

class Lists(list):

def __init__(self, *args, **kwargs):

super().__init__(*args, **kwargs)

# logic here, for now using the whole passed list

self.sides = self[:]

self.center = self[:]

def remove(self, obj):

# TODO catch ValueError that is raised if obj isn't in all of the lists

super().remove(obj)

self.sides.remove(obj)

self.center.remove(obj)

# probably overriding other methods from list, such as append, so

# an instance can be used directly to interact with the "master" list

my_lists = Lists(["first", "last", "middle", "top", "bottom", "left", "right", "inside"])

print(my_lists)

my_lists.remove('last')

print(my_lists)

print(my_lists.sides)

print(my_lists.center)

# ['first', 'last', 'middle', 'top', 'bottom', 'left', 'right', 'inside']

# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']

# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']

# ['first', 'middle', 'top', 'bottom', 'left', 'right', 'inside']

如果需要,您还可以更好地封装.master(如代码中的注释所示).

但是,您可能需要重新考虑问题以及您选择的解决问题的方法.可能有比保留原始列表的子列表更好的方法,并且还应记住,如果尝试从列表中删除不存在的元素,.remove将引发异常.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值