繁体   English   中英

编译列表:python最佳实践

[英]Compiling a list : python best practice

我经常在python 3中一次列出一个元素。 比如说我正在通过一个带有第一个元素head的链接列表来创建一个列表:

l = []
while head:
    l.append(head.val)
    head = head.next

我想知道什么是最佳做法。 还有另一种写方法吗? 可以用一行这样描述列表,而不是这样:

while head:
    l = # something creating the list AND appending elements
    head = head.next

甚至更好:我是否总是必须在类似情况下使用循环来创建列表,还是经常有一种方法可以在一行中制作所需的列表?

谢谢!

编辑:代码中有错字!

从OOP的角度来看,最佳实践是依靠Python的__iter__方法将可迭代对象转换为list

我假设您的链接列表class看起来像这样。

class LinkedList:
    def __init__(self, value, nxt=None):
        self.value = value
        self.next = nxt

要允许在链接列表上进行迭代,可以定义__iter__

class LinkedList:
    def __init__(self, value, nxt=None):
        self.value = value
        self.next = nxt

    def __iter__(self):
        while self:
            yield self.value
            self = self.next

然后,您可以让list处理可迭代的LinkedList

head = LinkedList(1, LinkedList(2, LinkedList(3)))
lst = list(head) # [1, 2, 3]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM