亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

Flask 應用程序的行為與動態列表和元組不符合預期

Flask 應用程序的行為與動態列表和元組不符合預期

慕勒3428872 2023-04-18 16:27:55
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]))


查看完整回答
反對 回復 2023-04-18
  • 1 回答
  • 0 關注
  • 122 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號