使用范围作为浮动对象的For循环

2024-10-03 17:17:23 发布

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

我想通过这个API访问多个页面。除了market_id之外,每个页面都有相同的URL。我想使用指定的范围,根据market_id循环浏览这些页面

for marketid in range(1.166871138,1.171064031):
    r = requests.get('https://betfair-data-supplier-prod.herokuapp.com/api/race_results/?market_id={marketid}&nz_tote_event_id=', headers={'User-Agent': 'Mozilla/5.0'}) 

当我使用这段代码时,我得到一个错误,说“float”对象不能解释为整数


Tags: inhttpsapiidurlfordataget
2条回答

如果要使用这些浮点对象作为for循环的范围,则需要将它们转换为整数并迭代这些对象

start = 1.166871138
stop = 1.171064031
step = 0.0001

startDecimals = len(str(start).split('.')[1]) # Get number of Decimal Points
endDecimals = len(str(stop).split('.')[1])
stepDecimals = len(str(step).split('.')[1])

maxDecimals = max(startDecimals, endDecimals, stepDecimals) # Which number has the most decimal points

# Go through them as integers
for i in range(int(start * 10**maxDecimals), int(stop * 10 **maxDecimals), int(step * 10**maxDecimals)):
    i =/(10 ** maxDecimals)
    print(i) # You can use this as the iterator value then

range()只接受值作为int,但是您可以输入您的输入范围作为乘以10的某事物的幂,这样结果将是int,然后对于每一轮循环,将marketid除以相同的10幂

例如:1.166871138*(10**9)=1166871138

因此,您的代码可能如下所示:

for marketid in range(1166871138, 1171064031):
   marketid/=10**9
   r = requests.get('https://betfair-data-supplier-prod.herokuapp.com/api/race_results/? 
   market_id={marketid}&nz_tote_event_id=', headers={'User-Agent': 'Mozilla/5.0'}) 

相关问题 更多 >