繁体   English   中英

如何计算python的价格金额

[英]How to count the amount of prices python

我试图从成功完成的网页中获取一些价格

prices = item.find_all("span", {"class": "price"})
for price in prices:
    price_end = price.text.strip().replace(",","")[2:]
    print(price_end)

输出为:

13
36
50
65
12
52
60
85

结果,我总共有8个价格。 我的问题是,如何使用Python自动计算输出中有多少价格?

我用len尝试过,但它只给了我相应数字的长度。

似乎直截了当,但我一直碰壁。

你们能帮我吗? 任何反馈表示赞赏。

count = 0
prices = item.find_all("span", {"class": "price"})
for price in prices:
    price_end = price.text.strip().replace(",","")[2:]
    count += 1
    print(price_end)
print(count, " prices found")

您可以将它们放在列表中:

price_list=[]
prices = item.find_all("span", {"class": "price"})
for price in prices:
    price_end = price.text.strip().replace(",","")[2:]
    price_list.append(price_end)

print(len(price_list))
print('\n'.join(price_list))

(如果您为每个条目输入一个价格,则len(prices)也可能会起作用...)

您可能需要将价格存储在列表中。 这是使用for循环的另一种方法。 这称为列表理解:

prices = [
    price.text.strip().replace(",","")[2:]
    for price in item.find_all("span", {"class": "price"})
]

这列出了价格。 然后,您可以打印价格数量和每个价格(此处使用字符串格式):

print("{price_count} prices: {prices}".format(
    price_count=len(price_list)),
    prices=prices,
)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM