gpt4 book ai didi

python - 使用就地切片扩展列表类

转载 作者:行者123 更新时间:2023-12-01 02:08:53 25 4
gpt4 key购买 nike

我正在尝试编写一个继承自 Python list 类的类,并具有一个可以进行就地切片(修改原始对象)的方法。

这就是我所拥有的:

class MyList(list):
def __init__(self, mylist = []):
list.__init__(self)
self.extend(mylist)
def slice_it(self, x):
self = self[:x]
return self

然后我实例化它:

>>> mylist = MyList(mylist=[1,2,3,4,5])
>>> mylist
[1, 2, 3, 4, 5]
>>> mylist.slice_it(3)
[1, 2, 3]
>>> mylist
[1, 2, 3, 4, 5]

我希望最后的输出是 [1, 2, 3]。有什么想法吗?

最佳答案

您只需分配给局部变量self,这不会改变列表。您必须使用 mutator 方法,因此请尝试:

class MyList(list):
def __init__(self, mylist = None):
list.__init__(self)
if mylist is not None:
self.extend(mylist)
def slice_it(self, x):
self[:] = self[:x]
return self

实际操作:

In [10]: mylist = MyList(mylist=[1,2,3,4,5])

In [11]: mylist
Out[11]: [1, 2, 3, 4, 5]

In [12]: mylist.slice_it(3)
Out[12]: [1, 2, 3]

In [13]: mylist
Out[13]: [1, 2, 3]

注意,您实际上可以使用切片表示法来完成此操作:

In [30]: from itertools import islice
...: class MyList(list):
...: def __init__(self, mylist = []):
...: list.__init__(self)
...: self.extend(mylist)
...: def __getitem__(self, x):
...: if isinstance(x, slice):
...: self[:] = islice(self, x.start, x.stop, x.step)
...: return self
...: else:
...: return list.__getitem__(self, x)
...:

In [31]: mylist = MyList(mylist=range(20))

In [32]: mylist[::2]
Out[32]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

In [33]: mylist
Out[33]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

In [34]: mylist[0]
Out[34]: 0

In [35]: mylist
Out[35]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

流畅的界面怎么样?

In [36]: mylist = MyList(mylist=range(100))

In [37]: mylist[::2][:10]
Out[37]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

In [38]: mylist
Out[38]: [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]

关于python - 使用就地切片扩展列表类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48835428/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com