python - 如何从python列表中的最小值开始?
问题描述
我想在列表中首先获得最低价格...这是我的代码
for link in productlinks:
try:
r = requests.get(link, headers=headers)
soup = BeautifulSoup(r.content, 'lxml')
name = soup.find(
'h1', class_='product-main__name').text.strip()
price = soup.find(
'p', class_='product-action__price').text.strip()
price = price.replace('£', '')
Aitems = {
'price': price,
'name': name
}
itemlist.append(Aitems)
print('Saving:', Aitems['price'])
except AttributeError:
continue
df = pd.DataFrame(itemlist)
print(min(df['price']))
输出:
Saving: 30.45
Saving: 31.95
Saving: 32.75
Saving: 32.95
Saving: 29.45
Saving: 38.95
Saving: 40.95
29.45
我可以获得该代码的最小值,但我想要整个“产品”列表,所以它从最小值开始直到最大值。
Output
name price
0 Suntory Torys Classic 30.45 < "I want it to start with the minimum value"
1 Suntory Toki 31.95
2 Akashi Blended Whisky 32.75
3 Tokinoka White Blended Whisky 32.95
4 Hatozaki Blended Japanese Whisky 29.45
5 Nikka Days 38.95
有什么简单的方法可以做到吗?
我试过了
print(df.sort_values(by=['price']))
但它没有排序最低价格。这是一种随机数。这是输出:
38 Ichiro's Malt Wine Wood Reserve 115
37 Ichiro's Malt MWR\nMizunara Wood Reserve 115
52 Suntory Yamazaki Puncheon\nBot.2013 1200
51 Suntory Yamazaki Bourbon Barrel\nBot.2013 1200
39 Suntory Yamazaki 12 Year Old 125
40 Okayama Single Malt 147
解决方案
我假设您使用的是 Pandas,因为您的代码中有一个“pd.Dataframe”。Pandas DataFrame 可以按以下方式排序
df = df.sort_values(by='price')
如果您的项目的索引应该被排序,另一种更通用的方法(不涉及熊猫)将生成一个列表。使用此 indexList,您可以对项目列表进行排序。
如何创建项目列表可以在这里查看如何在 Python 中获取已排序数组的索引。
用 numpy 创建 inxList 你会得到这个解决你问题的方法
import numpy as np
inxList = np.argsort([item['price'] for item in itemlist])
itemlist = [itemlist[inx] for inx in inxList]
推荐阅读
- python - 有 2 个最大值
- autocomplete - 为 Sublime 文本中的自定义语法启用自动完成
- r - 禁用 R 中的操作按钮面临多个输入的问题
- mysql - MySQL 帮助在表上迁移表模型和外键
- database - 如何使用 sqlflite 在数据库上保存日期时间?
- java - 我使用 LWJGL,当我使用 glfwCreateWindow 时,它卡住了我的代码
- windows - 从远程服务器渲染 jupyter notebook 时出现奇怪的线条而不是单元格
- python - 在 PyCham 中设置工作目录似乎不起作用
- django - Django模型:如果大小写匹配,如何更新值,否则保持当前值
- javascript - 优化及时确定许可证使用的过程