有没有办法在数组的拆分之间获取数字的开始和结束?

Is there a way to get the starts and ends of numbers between a split from an array?

对不起,我什至不知道给这个问题起什么标题。

我有一组数字,我称之为页面。

它们是我需要从浏览器中物理打印出来的页面。

pagesToPrint = [2,3,4,5,7,8,9,12,14,15,16,17,18,19,20]

现在,只打印 2,3,4,5,7...20 有什么问题?

将一页或多页发送到打印机后,发送和处理需要一段时间。因此,为了加快流程,最好只分批打印。说而不是打印 2-23-34-4 让我们只打印 2-5 我们不能打印 2-20 因为它会打印页面 6,10,11,13 等等上。

我真的不关心答案是哪种编程语言,而是它背后的逻辑。 最终我试图在 AutoHotkey 中解决这个问题。

嗯,你可以通过一点“top-down”的思考来解决这个问题。在理想的世界中,已经有一个函数可以调用:split_into_consecutive_batches(pages).

水平上,您如何描述它的工作原理?这基本上只是对您的初始 post 和要求稍微更精确的改写!

“好吧,只要页面列表左侧有页面,它就应该给我下一批。”

啊哈!

def split_into_consecutive_batches(pages):
  batches = []
  while pages:
    batches.append(grab_next_batch(pages))

  return batches

啊哈!那还不错,对吧?大的整体问题现在被简化为一个稍微小一点、稍微简单一点的问题。我们如何 获取下一批?好吧,我们抓住第一页。然后我们检查下一页是否是连续的页面。如果是,我们将其添加到批处理中并继续。如果没有,我们认为批处理完成并停止:

def grab_next_batch(pages):
  first_page = pages.pop(0)  # Grab (and delete) first page from list.
  batch = [first_page]

  while pages:
    # Check that next page is one larger than the last page in our batch:
    if pages[0] == batch[-1] + 1:
      # It is consecutive! So remove from pages and add to batch
      batch.append(pages.pop(0))
    else:
      # Not consecutive! So the current batch is done! Return it!
      return batch
  # If we made it to here, we have removed all the pages. So we're done too!
  return batch

应该可以了。虽然可以稍微清理一下;也许您不喜欢从页面列表中删除项目的 side-effect。而不是复制周围的东西,你可以找出索引。我会把它留作练习 :)