在迭代器中求和

时间:2019-04-08 06:28:06

标签: python

下面的代码显示所需的输出-10

Details
abort: 'https://xxxxx.visualstudio.com/xxxxx/_git/XXXXX' does not appear to be an hg repository:

svn: E170013: Unable to connect to a repository at URL 'https://xxxxx.visualstudio.com/xxxxx/_git/xxxxxx'
svn: E230001: Server SSL certificate verification failed: issuer is not trusted

如果我在这两行之间再添加一行代码,则输出更改为0

values = iter(range(1, 5))
sum(values)

1 个答案:

答案 0 :(得分:0)

Python iterators可耗尽的对象,这意味着它们在您调用它们时就被用尽。

  • 1 rst 示例:

    values = iter(range(1, 5))  # <- iterator is created
    sum(values)                 # <- all of it is used at once
    
  • 2 nd 示例:

    values = iter(range(1, 5))  # <- iterator is created
    values_list = list(values)  # <- all of it is used at once
    sum(values)                 # <- nothing left to sum :(
    

如果您想一遍又一遍地使用某些内容,iterator数据类型不适合您;改用list