gpt4 book ai didi

list - 将 List 的大小扩大 N

转载 作者:行者123 更新时间:2023-12-02 02:11:02 25 4
gpt4 key购买 nike

我很难表达这个问题,所以我对听起来含糊的标题表示歉意。

我今天开始学习Scala。我想生成一个元素列表,然后将该列表乘以因子 N,结果如下:

List(1, 2, 3, 4) * N -> List(1, 2, 3, 4, 1, 2, 3, 4) (where N = 2)

在Python中,我只需执行以下操作即可得到我想要的结果:

my_list = [1, 2, 3, 4] * 2 

但是,这在 Scala 中不起作用。

最佳答案

尝试List.fill

List.fill(2)(List(1, 2, 3, 4)).flatten
// : List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)

或者提供扩展方法来模仿Python,比如

extension (l: List[Int]) 
def *(n: Int): List[Int] = List.fill(n)(l).flatten

List(1, 2, 3, 4) * 2
// : List[Int] = List(1, 2, 3, 4, 1, 2, 3, 4)

关于list - 将 List 的大小扩大 N,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67759994/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com