scala - 如何在 Scala 中实现 Python 的 issuperset()

抱歉新手问题。我尝试用 Scala 类实现 Pythons issuperset()

Python 示例:

 weighted_fruits_set = {"banana", "orange","apple"}
 check = {"banana"}
 weighted_fruits_set.issuperset(check)

Python 答案:"True"

下面是我的 Scala 代码,我尝试包含case class weightedFruits 列表中找到superset,然后检查字符串 ” banana" 存在于 weightedFruits.name 中:

object Learn extends App {


  case class weightedFruits(name:List[String], weight:Double) {
override def toString = s"name: ${name.mkString("<", ",", ">")}, weight: $weight\n"
 }

 var weightedFruitsList = new scala.collection.mutable.ListBuffer[weightedFruits]()

 weightedFruitsList += ( 
                     weightedFruits(List("banana","orange"),180),
                     weightedFruits(List("banana","orange","apple"),170),                                 
                     weightedFruits(List("feijoa","fig"),201),
                     weightedFruits(List("banana","apple","melon"),165)
                     )

val check = weightedFruits(List("banana"),200)                       

weightedFruitsList += check                       

val item = weightedFruitsList(1)

val bol:Boolean = item.name.contains(check.name)

println("item: "+item)
println("check: "+check)
println("bool: "+bol)

}

我的代码的输出是false(但必须是true):

item: name: <banana,orange,apple>, weight: 170.0

check: name: <banana>, weight: 200.0

bool: false

感谢您的帮助。我真的希望我的解释很清楚

最佳答案

在我看来,当前的其他答案都超出了他们的需要。如果集合 A 是集合 B 的子集,那么 A 的所有元素都在 B 中。因此,如果我们从 A 中删除 B 的所有元素,应该什么也没有留下。所以

val a = List("banana") 
val b = List("banana", "orange","apple")
val c = List("tomato") 

(a diff b).isEmpty                                //> true
(c diff b).isEmpty                                //> false

(您没有指定如果“set”中的任何一个包含重复项应该发生什么)

如果你实际上使用的是集合而不是列表,这个操作已经在标准库中了

def subsetOf(that: GenSet[A]): Boolean

Tests whether this set is a subset of another set. that the set to test. returns true if this set is a subset of that, i.e. if every element of this set is also an element of that

参见 Scaladoc here

因此您可以使用 .toSet 将您的“集合”转换为实际集合,并使用它

https://stackoverflow.com/questions/39229727/

相关文章:

docker - 使用 Dockerfile 中的 COPY 在目标目录中复制具有不同名称的文件

maven - 将 Artifact 安装到特定的远程 Maven 存储库

python-3.x - pyspark中的异常值检测

SQL Server - 检查给定的日期+时间是否在两个日期时间变量之间的确切日期+时间

audio - 在网络服务器上播放 Apple 的 .caf 音频文件?

ios - 如何在 SwiftUI 中全屏显示 View ?

github - 如何从 GitHub 评论为我的拉取请求触发 Travis 重建?

prolog - '/1' 在 Prolog 中代表什么?

janusgraph - 如何在 Janusgraph 中获取索引键列表?

deployment - 如何在 Kubernetes 中相同部署的两个 Pod 中使环境变量不同?