sellers = ["amazon", "walmart", "Target", "CVS", "Walgreens", "macys", "kohls"]
data = [
{
"price": "21",
"title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
"seller": "kohls",
},
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "amazon"
},
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "macys"
},
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "walmart"
}
]
这是我的数据。我想按照上述列表按卖方对我的数据进行排序。 实际的列表必须是动态的。
请看看我该如何实现。
下面是我的
预期结果:
[
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "amazon"
},
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "walmart"
},
{
"price": "21.00",
"title": "Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream",
"seller": "macys"
},
{
"price": "21",
"title": "Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl",
"seller": "kohls",
}
]
请看看
答案 0 :(得分:2)
您可以使用sorted()
res = sorted(data, key=lambda x: sellers.index(x['seller']))
print(res)
输出:
[{'price': '21.00',
'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
'seller': 'amazon'},
{'price': '21.00',
'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
'seller': 'walmart'},
{'price': '21.00',
'title': 'Laura Geller Beauty Iconic Baked Sculpting Lipstick - Cream',
'seller': 'macys'},
{'price': '21',
'title': 'Laura Geller Iconic Baked Sculpting Lipstick, Red Overfl',
'seller': 'kohls'}]