Skip to main content
 首页 » 编程设计

Python(Flask) 变硬排序服装排序

2025年05月04日1498°冷暖

我有这样的 json:

[ 
    { 
        "product_variants": [ 
            { 
                "id": 1669, 
"attributes": [ 
                    { 
                        "name": "size", 
                        "value": "XXS" 
                    }, 
                    { 
                        "name": "color", 
                        "value": "Pink" 
                    } 
                ] 
    },{ 
                "id": 1670, 
"attributes": [ 
                    { 
                        "name": "size", 
                        "value": "XS" 
                    }, 
                    { 
                        "name": "color", 
                        "value": "Black" 
                    } 
                ] 
    } 
     "id": 834, 
        "name": "Acute Cardigan" 
    }, ....] 

我如何通过关闭大小对 product_variants 进行排序。订单必须按尺寸:

 SORT_ORDER = ["S", "M", "L", "XL", "2XL", "3XL", "4XL", "5XL", "6XL"] 

我只有输出 XXL 等的代码...如果你能给我一些建议

    for product in products: 
        for product_variant in product.product_variants: 
            for attribute in product_variant.attributes: 
                if attribute['name'].lower() in "size": 
                    pring(['attribute']) //print XXL... 

请您参考如下方法:

您可以创建一个字典并使用将用作排序键的值映射所有尺寸:

SORT_ORDER = {"S" : 0, "M" : 1, "L" : 2, "XL" : 3, "2XL" : 4, "3XL" : 5, "4XL" : 6, "5XL" : 7, "6XL" : 8} 

然后您可以根据这些值的键执行排序:

productVariants = [{"product_variants" : sorted(productVariants[0]['product_variants'], key=lambda elem: SORT_ORDER[elem['attributes'][0]['value']])}] 

例如:

productVariants = [{"product_variants":[{"id":1669,"attributes":[{"name":"size","value":"M"},{"name":"color","value":"Pink"}]},{"id":1670,"attributes":[{"name":"size","value":"S"},{"name":"color","value":"Black"}]}]}] 
 
SORT_ORDER = {"S" : 0, "M" : 1, "L" : 2, "XL" : 3, "2XL" : 4, "3XL" : 5, "4XL" : 6, "5XL" : 7, "6XL" : 8} 
 
productVariants = [{"product_variants" : sorted(productVariants[0]['product_variants'], key=lambda elem: SORT_ORDER[elem["attributes"][0]['value']])}] 
 
print(productVariants) 

这将返回:

[{'product_variants': [{'id': 1670, 'attributes': [{'name': 'size', 'value': 'S'}, {'name': 'color', 'value': 'Black'}]}, {'id': 1669, 'attributes': [{'name': 'size', 'value': 'M'}, {'name': 'color', 'value': 'Pink'}]}]}]