Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/353.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
带列表的Python循环_Python_For Loop_Python 3.x - Fatal编程技术网

带列表的Python循环

带列表的Python循环,python,for-loop,python-3.x,Python,For Loop,Python 3.x,我正在编写一些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('Th

我正在编写一些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程序员那里了解:


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

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

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


然而,如果你想在这种迭代的基础上制作一个
列表
,那么你当然应该使用列表理解。

代码美观/可维护性是一个棘手的问题。这真的取决于你和你的同事


有很长一段时间,我对列表的理解等感到不舒服,我更喜欢用第一种方式来写,因为这样我更容易阅读。然而,与我共事的一些人更喜欢第二种方法。

如果它只使用副作用,则不会。