首页 > 解决方案 > 在 for 循环中对特定索引进行计算

问题描述

我尝试编写一个小程序以使我的工作更轻松,但我无法理解最后一个重要部分。我对 python 还很陌生,并且非常高兴我能走到这一步。

代码遍历 6 页并从表中提取信息并给出。

我现在需要做的是计算 1% 到第 4 个输出值,即循环索引 3 (564,09*1.01) - 其余的应该在没有计算的情况下输出。我想我需要if else在最后一个for循环中声明,但我无法让它工作:(

我的代码如下:

# Import libraries
import requests
from bs4 import BeautifulSoup

metalle = ['Ag_processed','Al_cables','Au_processed','DEL_low','MB_MS_63_wire','Pb_Cable']
urls = []
for i in metalle:
    url = 'http://somepage.com/yada.php?action=show_table&field=' + str(i)
    urls.append(url)

for y in urls:
    page = requests.get(y)
    soup = BeautifulSoup(page.text, 'html.parser')

# Remove links
    last_links = soup.find(class_='linkbar')
    last_links.decompose()
    years = soup.find(class_='year')
    years.decompose()

# Pull all text from the section div
    tabelle = soup.find(class_='section')

# Pull text from all instances of <tr> tag within section div, ignore first one, header 1:
    preise = tabelle.find_all('tr')[1:]

# Create for loop to print out all prices
    wert = []
    for tabelle in preise:
    #I FIGURE HERE IS A IF ELSE NEEDED
        preis = tabelle.contents[1]
        wert.append(preis.string)
    print(wert[0])

OUTPUT: 
474,60  
213,06  
38.550,00 
564,09 #THIS NEEDS TO BE CALCULATED +1%
557,00
199,55

我希望你能帮助一个 Python 新手 <3

问候桑德里戈

标签: pythonpython-3.x

解决方案


您可以preise使用方法将列表转换为枚举类型enumerate()。这意味着,如果您的列表看起来像这样["a", "b", "c"],您可以将其转换为[(0, "a"), (1, "b"), (2, "c"]. 因此,您的代码必须如下所示:

for i, tabelle in enumerate(preise):
    if i == 3:
       preis = tabelle.contents[1]*1.01
    else:
       preis = tabelle.contents[1]
    wert.append(preis.string)

推荐阅读