【问题标题】:How to extract every n continuous elements in a list in scala? [duplicate]如何提取scala列表中的每n个连续元素? [复制]
【发布时间】:2017-07-17 16:49:35
【问题描述】:

只是说我有一个包含 100 个元素的列表。我想提取长度 = 5 的列表(即,将有 20 个提取的列表,即元素 0-4、5-9、...)。有什么优雅的方法可以做到这一点?

【问题讨论】:

    标签: scala


    【解决方案1】:

    你需要group by每个块中有多少元素

    scala> (0 to 99).toList.grouped(5).toList
    res5: List[List[Int]] = List(List(0, 1, 2, 3, 4), List(5, 6, 7, 8, 9), List(10, 11, 12, 13, 14), List(15, 16, 17, 18, 19), List(20, 21, 22, 23, 24), List(25, 26, 27, 28, 29), List(30, 31, 32, 33, 34), List(35, 36, 37, 38, 39), List(40, 41, 42, 43, 44), List(45, 46, 47, 48, 49), List(50, 51, 52, 53, 54), List(55, 56, 57, 58, 59), List(60, 61, 62, 63, 64), List(65, 66, 67, 68, 69), List(70, 71, 72, 73, 74), List(75, 76, 77, 78, 79), List(80, 81, 82, 83, 84), List(85, 86, 87, 88, 89), List(90, 91, 92, 93, 94), List(95, 96, 97, 98, 99))
    

    见 - Split list into multiple lists with fixed number of elements

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-05-04
      • 1970-01-01
      • 1970-01-01
      • 2018-02-07
      • 1970-01-01
      • 2011-03-19
      • 2016-11-04
      • 2018-03-11
      相关资源
      最近更新 更多