a = [2, 237, 3, 10]b = (0, 0, {'product_id': '', 'product_uom_qty': ''}), (0, 0, {'product_id': '', 'product_uom_qty': ''})start_index = 0b = list(b)for b_entry in b:    end_endex = start_index + len(b_entry[2]) - 1    for value in range(start_index, end_endex):        b_entry[2]['product_id'] = a[value]        b_entry[2]['product_uom_qty'] = a[value + 1]    start_index += len(b_entry[2])print(b)按需工作并产生[(0, 0, {'product_id': 2, 'product_uom_qty': 237}), (0, 0, {'product_id': 3, 'product_uom_qty': 10})]但是在烧瓶应用程序中 @app.route('/listener', methods=['POST'])def listener():    if request.method == 'POST':        content = request.json        logging.info(content)        invnm = content[0]['InvoiceNumber']        fx = content[0]['InvoiceNumberPrefix']        customer = content[0]['CustomerID']        noi = (len(content[0]['OrderItemList']))        itersandid = []        changetos = {'672': 2,             '333': 3}        for d in content:            for i in d["OrderItemList"]:                itersandid.append(i.get("ItemID"))                itersandid.append(i.get("ItemQuantity"))        a = [changetos.get(x, x) for x in itersandid]        sales = (0, 0, {'product_id':'','product_uom_qty':''}),        b = []        b.extend(sales*noi)        print(a)        print(b)        start_index = 0        b = list(b)        for b_entry in b:            end_endex = start_index + len(b_entry[2]) - 1            for value in range(start_index, end_endex):                b_entry[2]['product_id'] = a[value]                b_entry[2]['product_uom_qty'] = a[value + 1]            start_index += len(b_entry[2])        print(b)有时候是这样的[(0, 0, {'product_id': 3, 'product_uom_qty': 10}), (0, 0, {'product_id': 3, 'product_uom_qty': 10})]结果应该是一样的,我不明白为什么不一样。我已经打印了 a 和 b 并确认它们是正确的,但是索引一定有问题,但我不确定它可能是什么。
                    
                    
                1 回答
 
                    
                    
                            Smart猫小萌
                            
                                
                            
                        
                        
                                                
                    TA贡献1911条经验 获得超7个赞
好像问题就在这里:
sales = (0, 0, {'product_id':'','product_uom_qty':''}),
b = []
b.extend(sales*noi)
{'product_id':'','product_uom_qty':''}是一个对象,您不克隆它,只需以这种方式复制其引用即可。因此 for 循环在每次迭代时都会更改相同的实例。这就是为什么您在每个副本中都有最后一次迭代的结果。
快速解决:
b = [(0, 0, {'product_id':'','product_uom_qty':''}) for _ in range(noi)]
您的示例之所以有效,是因为您这样声明它:
b = (0, 0, {'product_id': '', 'product_uom_qty': ''}), (0, 0, {'product_id': '', 'product_uom_qty': ''})
您初始化了两个不同的对象,因此它按预期工作。
这是一个非常棘手的问题,谢谢你的谜题:)
奖励:如果你想证明它实际上是同一个对象,你可以将这段代码粘贴到两个片段中:
print(id(b[0][2]))
print(id(b[1][2]))
添加回答
举报
0/150
	提交
		取消
	