【问题标题】:Creating a list of set of pairs from existing list从现有列表创建一组对列表
【发布时间】:2021-07-10 18:34:30
【问题描述】:

假设我有以下列表:

val my_list = List("a","b","c","d")

我想写一个函数get_set_pairs 这样get_set_pairs(my_list) 给我:

List(Set("a","b"), Set("a","c"), Set("a","d"), Set("b","c"), Set("b","d"), Set("c","d"))

我知道如何使用 for 循环来做到这一点。我正在尝试找到一种实用且有效的方法

感谢您的帮助

【问题讨论】:

  • 首先,请遵循命名约定:getSetPairs 这不是 Python。 - 第二,为什么Sets 有两个元素?只需使用 元组。第三,您可以只使用for comprehension 编写与命令式for 循环 非常相似的代码。 - 最后,如果你know the rules of the sugar syntax of for,你会发现你可以很容易地使用flatMapmap & filter

标签: list scala set


【解决方案1】:

您可以使用combinations 并将条目映射到集合:

my_list.combinations(2).map(_.toSet).toList
// List[scala.collection.immutable.Set[String]] = List(Set(a, b), Set(a, c), Set(a, d), Set(b, c), Set(b, d), Set(c, d))

【讨论】:

    猜你喜欢
    • 2020-05-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-15
    • 2018-09-24
    • 2021-03-02
    • 1970-01-01
    • 2014-03-10
    相关资源
    最近更新 更多