首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在python中从列表中的最小值开始?

问如何在python中从列表中的最小值开始?
EN

Stack Overflow用户
提问于 2020-10-13 01:07:46
回答 1查看 54关注 0票数 1

我想在列表中先得到最低价格...这是我的代码

代码语言:javascript
复制
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']))

输出:

代码语言:javascript
复制
Saving: 30.45
Saving: 31.95
Saving: 32.75
Saving: 32.95
Saving: 29.45
Saving: 38.95
Saving: 40.95
29.45

我可以得到该代码的最小值,但我想要“产品”的整个列表,因此它从最小值开始直到最大值。

代码语言:javascript
复制
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

有没有简单的方法可以做到这一点?

我试过了

代码语言:javascript
复制
print(df.sort_values(by=['price']))

但它没有对最低价格进行排序。这是一种随机数字。下面是输出:

代码语言:javascript
复制
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
EN

回答 1

Stack Overflow用户

发布于 2020-10-13 01:32:33

我假设您使用的是Pandas,因为您的代码中有一个"pd.Dataframe“。Pandas DataFrame可以按以下方式排序

代码语言:javascript
复制
df = df.sort_values(by='price')

另一种更通用的方法(不涉及熊猫)是生成一个列表,如果你的项目应该排序的话。使用此indexList,您可以对项目列表进行排序。

如何创建项目列表可以在这里查看How to get indices of a sorted array in Python。

使用numpy创建inxList,您将获得此问题的解决方案

代码语言:javascript
复制
import numpy as np
inxList = np.argsort([item['price'] for item in itemlist])
itemlist = [itemlist[inx] for inx in inxList]
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64322267

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档