我已经制作了一个包含描述和价格的数组,但似乎无法让 sortign 按价格排序。有人可以帮助或指导我为什么不能正确按价格排序吗?我检查了价格类型,它是浮动的。据我了解,它应该有效。我也没有收到错误。然而,输出不按价格排序。 :/
构建数组
import array
newlist = []
for d in products:
desc =d.description
price=d.price
#print(type(price))
newlist.append(f"{desc}:{price}")
新列表输出
['Coors Light American-style Light Lager Beer:16.99', 'Coors Light American-style Light Lager Beer:26.99', 'Michelob ULTRA Superior Light Domestic Lager Beer:18.99', 'Samuel Adams Summer Ale Seasonal Beer:19.99', 'Miller Lite American Pilsner Light Lager Beer:22.99', 'Miller Lite American Pilsner Light Lager Beer:26.99', 'Michelob ULTRA Superior Light Domestic Lager Beer:26.99', 'Bud Light Lager Beer:32.99', 'Samuel Adams Summer Ale Seasonal Beer:10.99', 'Michelob ULTRA Superior Light Domestic Lager Beer:33.99', 'Busch Light Domestic Lager Beer:31.99', 'Michelob ULTRA Superior Light Domestic Lager Beer:26.99', 'Coors Banquet American Lager Beer:16.99', 'Stella Artois Premium Lager Beer:20.99', 'Michelob ULTRA Superior Light Domestic Lager Beer:34.99', "Leinenkugel's Summer Shandy Craft Beer:19.99", 'Coors Light American-style Light Lager Beer:22.99', 'Blue Moon Belgian-Style Ale White Wheat Beer:19.99', 'Blue Moon Belgian-Style Ale White Wheat Beer:19.99', 'Heineken Original Lager Beer, 12 Pack, 12 fl oz Bottles:20.99']
尝试按价格排序
import operator
getcount = itemgetter(int(1))
list(map(getcount, newlist))
sortedlist = sorted(newlist, key=getcount)
for l in sortedlist:
print(l)
输出
Samuel Adams Summer Ale Seasonal Beer:10.99
Leinenkugel's Summer Shandy Craft Beer:19.99
Heineken Original Lager Beer, 12 Pack, 12 fl oz Bottles:20.99
Michelob ULTRA Superior Light Domestic Lager Beer:18.99
Miller Lite American Pilsner Light Lager Beer:22.99
Miller Lite American Pilsner Light Lager Beer:26.99
Michelob ULTRA Superior Light Domestic Lager Beer:26.99
Michelob ULTRA Superior Light Domestic Lager Beer:33.99
Michelob ULTRA Superior Light Domestic Lager Beer:26.99
Michelob ULTRA Superior Light Domestic Lager Beer:34.99
Blue Moon Belgian-Style Ale White Wheat Beer:19.99
Blue Moon Belgian-Style Ale White Wheat Beer:19.99
Dos Equis Mexican Lager Beer, 12 Pack, 12 fl oz Bottles:19.99
Coors Light American-style Light Lager Beer:16.99
Coors Light American-style Light Lager Beer:26.99
Coors Banquet American Lager Beer:16.99
Coors Light American-style Light Lager Beer:22.99
Stella Artois Premium Lager Beer:20.99
Bud Light Lager Beer:32.99
Busch Light Domestic Lager Beer:31.99
您可以使用 lambda 函数作为
key
:
newlist = [(d["description"], d["price"]) for d in products]
s = sorted(newlist, key=lambda x: x[1])
print(s)