python - 在 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
问候桑德里戈
解决方案
您可以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)
推荐阅读
- python - Keras2 ImageDataGenerator 或 TensorFlow tf.data?
- r - 如何在survminer(ggforest)中向森林图添加箭头
- c++ - 服务器可以接受来自另一个子网的连接吗?
- javascript - 如何将深层表单数据作为数组或对象发送?
- python - 使用 Databricks 将 Google Api 的结果写入数据湖
- c# - 我的 css 文件不适用于 xmlworkloader
- c# - 如何使用 C# 使表格中的文本在 PowerPoint 上具有轮廓?
- pytorch - 使用 2d 张量索引 3d 张量
- java - 我在哪里可以下载 Java Mission Control(7)(OpenJDK11 或更高版本)?
- javascript - 从正文中获取所有文本并根据标签拆分