簡體   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