【问题标题】:Python loop with lists带有列表的 Python 循环
【发布时间】:2011-06-11 22:26:34
【问题描述】:

我正在编写一些 Python 3.2 代码,我想到了这个问题:

我有这些变量:

# a list of xml.dom nodes (this is just an example!)
child_nodes = [node1, node2, node3]
# I want to add every item in child_node into this node (this also a xml.dom Node)
parent = xml_document.createElement('TheParentNode')

这正是我想做的:

for node in child_nodes:
    if node is not None:
        parent.appendChild(node)

我是这样写的:

[parent.appendChild(c) for c in child_nodes if c is not None]

我根本不会使用列表结果,我只需要 appendChild 来完成它的工作。

我不是一个很有经验的python程序员,所以我想知道哪个更好? 我喜欢单行解决方案,但我想向有经验的python程序员了解:

在代码美观/可维护性和性能/内存使用方面,哪个更好。

【问题讨论】:

    标签: python for-loop python-3.x


    【解决方案1】:

    在这种情况下,前者更可取。

    后者称为list comprehension 并创建一个新的list 对象,其中包含每次调用parent.appendChild(c) 的结果。 然后丢弃它

    但是,如果您想要基于这种迭代创建list,那么您当然应该使用列表推导式。

    【讨论】:

      【解决方案2】:

      代码美观/可维护性问题是一个棘手的问题。这真的取决于您和您的合作伙伴来决定。

      很长一段时间以来,我对列表推导等感到不舒服,并且更喜欢以第一种方式编写它,因为它更容易阅读。然而,与我一起工作的一些人更喜欢第二种方法。

      【讨论】:

      • 如果它只使用副作用则不会。
      猜你喜欢
      • 2013-07-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-26
      • 2021-04-19
      • 1970-01-01
      • 2017-02-25
      相关资源
      最近更新 更多