【问题标题】:hHw to loop a number to fill a list alternatelyhHw 循环一个数字以交替填充列表
【发布时间】:2019-07-17 19:52:25
【问题描述】:

我有下面显示的代码,我正在尝试打印一个数字来填写列表。 i 这里的值将索引到另一个列表。如何循环以使列表“(urls [i])”中i的值始终从零变化,直到达到长度值。

我已经尝试过了,但它唯一的打印数字是 1-8(这是名为 url 的列表的长度)

length=len(urls) //this is my input, the value of urls will 
            // depend on the result of my previeous code
i=0
while i<length:
  print(i)
  i += 1
result2 = requests.get(urls[i]) ///i want the value of i here  
        // to be increased by 1 everytime its looping
src2 = result2.content
soup = BeautifulSoup(src2, 'lxml')
links2 = soup.find_all('p')
print(links2)

【问题讨论】:

  • 你给length分配了一些东西,但从未使用过;你使用num,但从不分配任何东西给它。这意味着发布的代码在尝试使用num时会失败。
  • 你能提供一个更好的例子来说明你有什么和你想要什么吗? (输入和输出)。根据所提供的措辞和示例,很难理解您的问题。干杯。
  • while i&lt;length:

标签: python-3.x list loops


【解决方案1】:

我认为你只需要缩进你的代码:

while i<length:
  print(i)
  i += 1
  //i want the value of i here to be increased by 1 everytime its looping
  result2 = requests.get(urls[i])
  src2 = result2.content
  soup = BeautifulSoup(src2, 'lxml')
  links2 = soup.find_all('p')
  print(links2)

【讨论】:

    猜你喜欢
    • 2021-12-23
    • 1970-01-01
    • 2016-11-25
    • 2020-05-25
    • 1970-01-01
    • 2016-02-23
    • 2019-01-29
    • 2021-05-21
    • 2021-07-06
    相关资源
    最近更新 更多