【问题标题】:What is the way to separate range and pass the array to the function? [duplicate]分离范围并将数组传递给函数的方法是什么? [复制]
【发布时间】:2014-04-15 21:40:05
【问题描述】:

我有 attachmentList 的数组和

如果我这样做

len(attachmentList) 

结果是 199930; 我想每次向 api_request(attachment) 函数发送 999 个元素

所以伪代码会是这样的

count=0
for (i=0,i<len(attachmentList),i++)
     count++
     if count=999:
       api_request(attachmentList[i-999:i])
       count=0

for循环的写法是什么,或者有另一种解决方案。

【问题讨论】:

标签: python


【解决方案1】:

使用grouper recipe

def grouper(iterable, n, fillvalue=None):
    "Collect data into fixed-length chunks or blocks"
    # grouper('ABCDEFG', 3, 'x') --> ABC DEF Gxx
    args = [iter(iterable)] * n
    return izip_longest(fillvalue=fillvalue, *args)

然后:

for chunk in grouper(attachmentList, 1000):
    api_request(chunk)

【讨论】:

    【解决方案2】:

    你可以循环 999 个块:

    for i in range(0, len(attachmentList), 999):
        api_request(attachmentList[i:i+999])
    

    【讨论】:

      【解决方案3】:

      您可以将range(...) 函数用作:

      previous = 0
      for i in range(999,len(attachmentList),999):
          api_request(attachmentList[previous:i]
          previous = i
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-04-03
        • 2018-06-26
        • 1970-01-01
        • 2013-05-11
        • 1970-01-01
        • 1970-01-01
        • 2015-04-23
        相关资源
        最近更新 更多