首页 > 解决方案 > 插入节点替换python中的前一个节点

问题描述

我想将多个值附加到这个节点(如果它发生),但是当我这样做时 productid2 替换 productid1。有没有办法返回单独的产品 ID 项目?

           for node in tree.xpath( '//map/topicmeta' ):
                node.insert(5, othermeta)                       
                othermeta.set("name", "product-id")
                othermeta.attrib['content'] = meta_productid1

                othermeta.set("name", "product-id")
                othermeta.attrib['content'] = meta_productid2

标签: pythonxpath

解决方案


您可以使用listortuple来存储多个项目:

othermeta.attrib['content'] = []
othermeta.attrib['content'].append(meta_productid1)
othermeta.attrib['content'].append(meta_productid2)

或者

othermeta.attrib['content'] = [meta_productid1, meta_productid2]
othermeta.attrib['content'] = (meta_productid1, meta_productid2)

您可以通过以下方式获得它们:

id1, id2 = othermeta.attrib['content']

如果 type ofothermeta.attrib['content']被限制为str,你可以连接id1 id2到 one str,并在你使用的地方解析它:

店铺:

othermeta.attrib['content'] = ','.join([meta_productid1, meta_productid2])

利用:

id1, id2 = othermeta.attrib['content'].split(',')

希望我对你的问题没有误解。


推荐阅读