我有這個(gè)元組列表,如下所示:
[(21, 2, 10.0), (21, 104, 20.0), (22, 1, 371.0), (22, 104, 742.0), (23, 1, 114.0), (23, 104, 228.0), (25, 1, 2.0), (25, 104, 2.0)]
每個(gè)數(shù)字的上下文按順序是 id、sku_id 和數(shù)量。目標(biāo)是遍歷具有相同 ID 的每批元組并執(zhí)行以下操作:
檢查 sku_id 為 104 的任何條目在同一 quote_id 中是否有另一個(gè)條目
其他條目的數(shù)量必須是前一行的一半。
在上面的示例中,id 為 25 的行將匹配,因?yàn)?sku_id 為 1 的行的數(shù)量不是 sku_id 104 的行的一半。這應(yīng)該附加到最終集。
怎樣才能做到這一點(diǎn)?
以用來collections.defaultdict制作訂單字典:
all_orders = defaultdict(dict) for i, sku, qty in data: all_orders[i][sku] = qty
all_orders就是現(xiàn)在:
{ 21: {2: 10.0, 104: 20.0}, 22: {1: 371.0, 104: 742.0}, 23: {1: 114.0, 104: 228.0}, 25: {1: 2.0, 104: 2.0} }
然后循環(huán)查看它們是否符合標(biāo)準(zhǔn)文章來源:http://www.zghlxwxcb.cn/article/280.html
for i, orders in all_orders.items(): if 104 not in orders: continue if len(orders) == 1: print("Needs to be more than one order if sku is 104") continue half_104_qty = orders[104] / 2 for qty in orders.values(): if qty < half_104_qty: continue else: print("There must be another order half the quantity of the order with sku 104")
文章來源地址http://www.zghlxwxcb.cn/article/280.html
到此這篇關(guān)于Python 在迭代 for 循環(huán)時(shí)檢查其他行的文章就介紹到這了,更多相關(guān)內(nèi)容可以在右上角搜索或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!