gpt4 book ai didi

python - 在Python中实现自定义可迭代对象

转载 作者:太空宇宙 更新时间:2023-11-03 15:51:38 25 4
gpt4 key购买 nike

这是我在 Python 中实现的自定义单链表。

 class SList:
def __init__(self):
self.root = None
self.size = 0

def insert(self, item):
if not item:
raise ValueError('Cannot add None item to a list')
self.size += 1
if self.root is None:
self.root = Node(item)
else:
p = Node(item)
p.next = self.root
self.root = p

"""Remove the element at the specific index"""
def remove(self, index):
if index < 0 or index >= self.size:
raise ValueError('Index cannot be negative or greater than the size of the list')

current = self.root
if index == 0:
self.root = self.root.next
else:
for _ in range(index -1):
current = current.next
p = current.next.next
if p is not None:
current.next = p
else:
current.next = None

self.size -= 1

def __len__(self):
return self.size

def __repr__(self):
res = '[ '
current = self.root
while current is not None:
res += str(current.data)
res += ' '
current = current.next
res += ']'
return res

def __iter__(self):
return self

def next(self):
........

这是节点对象

class Node:
def __init__(self, data):
try:
if not data:
raise ValueError
self.data = data
self.next = None
except ValueError:
raise ValueError('Node cannot be instantiated without an item')

我在实现 iter 方法时有点不知所措。我看到有多种方法可以实现它,并且yield 似乎是常见的前进方式。希望能在使用 yield

实现它时得到一些帮助

最佳答案

您可以通过将类的 __iter__ 方法设置为生成器来使其可迭代。

以下是一些在 Python 2 或 Python 3 上正确运行的代码。

from __future__ import print_function

class Node(object):
def __init__(self, data):
if data is None:
raise ValueError('Node cannot be instantiated without an item')
self.data = data
self.nextnode = None

def __repr__(self):
return 'Node({})'.format(self.data)

class SList(object):
def __init__(self):
self.root = None
self.size = 0

def insert(self, item):
if item is None:
raise ValueError('Cannot add None item to a list')
self.size += 1
if self.root is None:
self.root = Node(item)
else:
p = Node(item)
p.nextnode = self.root
self.root = p

def remove(self, index):
""" Remove the element at the specific index """
if index < 0 or index >= self.size:
raise ValueError('Index cannot be negative or greater than the size of the list')

current = self.root
if index == 0:
self.root = self.root.nextnode
else:
for _ in range(index - 1):
current = current.nextnode
current.nextnode = current.nextnode.nextnode

self.size -= 1

def __len__(self):
return self.size

def __repr__(self):
res = []
current = self.root
while current is not None:
res.append(current.data)
current = current.nextnode
return str(res)

def __iter__(self):
current = self.root
while current is not None:
yield current
current = current.nextnode

# test

a = SList()
for c in 'ABCDE':
a.insert(c)

print(a)

gen = iter(a)
print('root', next(gen))
for node in gen:
print(node)

a.remove(2)

print(list(a))

for node in a:
print(node)

输出

['E', 'D', 'C', 'B', 'A']
root Node(E)
Node(D)
Node(C)
Node(B)
Node(A)
[Node(E), Node(D), Node(B), Node(A)]
Node(E)
Node(D)
Node(B)
Node(A)

关于python - 在Python中实现自定义可迭代对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41235916/

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