如何创建自己的列表iterable而不使用子类?

2024-10-01 17:38:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在学习Python,开发了一些web应用程序等。现在,我想更深入地了解Python的底层工作原理。为此,我想把我自己的清单列出来。以下是我迄今为止的努力:

 class CustomList:
    def __init__(self,*args):
        self.nums=args
        self.count=0
        i=0
        for arg in args:
            i+=1
        self.total=i

    def __iter__(self):
        return self

    def __next__(self):
        if self.count >= self.total:
            raise StopIteration
        self.count+=1

mylist=CustomList(1,2,3,4)
for item in mylist:
    print(item)

现在,在我的next函数中,我不确定如何迭代我的self.nums,以便我的print(item)逐个打印self.nums中的每个项目

我真的不想使用任何与len()、append()等相关的东西。我想自己创建它们。所以这就是未来的计划。现在,我甚至不能遍历用户给定的*args


Tags: inselfweb应用程序fordefcountargs
1条回答
网友
1楼 · 发布于 2024-10-01 17:38:10

你需要回到另一个层次。MyList中的args(*args)已经是iterable。 每个列表项都需要显式指向下一个。因此,每个列表项都需要下一个指针的记录以及与之相关联的数据。这可以是dict,但是MyList.append需要显式访问记录。对我来说MyListItem类更清晰

class MyListItem:
    def __init__(self, data):
        self.next = None
        self.data = data

    def link_to(self, child):
        self.next = child

MyList类可以使用它作为列表结构中的节点。可能有更好的实现,但这是我能得到的最基本的

class MyList:
    def __init__(self):
        """ Create the list header record, initialised to an empty list. """
        self.top = None
        self.bottom = None
        self.curr = None    # Used to iterate through the list.

    def append(self, data):
        node = MyListItem(data) # Create the List item 
        if self.top is None:    # If the list is empty point top to node
            self.top = node
        else:
            self.bottom.link_to(node) # Otherwise point the bottom node to the new node
        self.bottom = node            # Point the bottom to the new node

    def __iter__(self): 
        self.curr = self.top      # Initialise the current pointer to top
        return self

    def __next__(self):
        if self.curr:                   # If the curr pointer is not None
            res = self.curr.data        # Get the data
            self.curr = self.curr.next  # Set curr to next
            return res                  # Return the data
        else:
            raise StopIteration

测试一下

test = MyList()

test.append(1)
test.append('Two')
test.append([1, 2, 3])

for node in test:
    print(node)

1
Two
[1, 2, 3]

相关问题 更多 >

    热门问题