问题描述
pt-0 pb-3
输出:
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']))
解决方法
我假设您正在使用Pandas,因为您的代码中有一个“ pd.Dataframe”。 熊猫数据框的排序方式为
df = df.sort_values(by='price')
如果应该对项目的索引进行排序,则另一种更通用的方式(不涉及熊猫)将生成列表。使用这个indexList可以对项目列表进行排序。
如何创建项目列表可以在此处How to get indices of a sorted array in Python中看到。
使用numpy创建inxList可以解决您的问题
import numpy as np
inxList = np.argsort([item['price'] for item in itemlist])
itemlist = [itemlist[inx] for inx in inxList]