在一个 for 循环中对特定索引进行计算

2024-09-28 23:40:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着编写一个小程序,使我的工作更容易,但我不能让我的头周围的最后一个重要的部分。我对python还相当陌生,并且非常高兴我已经走了这么远。你知道吗

代码遍历6页,从表中提取信息并给出。你知道吗

我现在需要做的是计算1%到第四个输出值,也就是循环指数3(564,09*1.01),剩下的应该不计算出来。我想我需要在最后一个for循环中使用一个if else语句,但我无法让它工作:(

我的代码如下:

# 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

你好,桑德里戈


Tags: 代码textinfromimportforsectionlinks
3条回答

好了,伙计们,谢谢大家的帮助,我想:

工作方案:

for (i, y) in enumerate(urls):
    page = requests.get(y)
    soup = BeautifulSoup(page.text, 'html.parser')
    last_links = soup.find(class_='linkbar')
    last_links.decompose()
    years = soup.find(class_='year')
    years.decompose()
    tabelle = soup.find(class_='section')
    preise = tabelle.find_all('tr')[1:]
    wert = []
    for tabelle in preise:
        if i == 3:
            preis = tabelle.contents[1]
            wert.append(preis.string)
            wert[0] = str(wert[0]).replace('.', '').replace(',', '.') 
            wert[0] = float(wert[0]) * 1.01
            wert[0] = str(wert[0]).replace('.', ',')
            break
        else:
            preis = tabelle.contents[1]
            wert.append(preis.string)   
    print(wert[0])

    file.write(str(wert[0]))
    file.write("\n")
file.close()

谢谢大家!你知道吗

在代码末尾,您可以

# format currency to valid number, from 38.550,00 to 38550.00 
wert[3] = wert[3].replace('.', '').replace(',', '.') 
wert[3] = float(wert[3]) * 1.01
print(wert)

可以使用方法enumerate()将列表preise转换为枚举类型。它的意思是,如果你的列表看起来像这样["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)

相关问题 更多 >