抱歉新手问题。我尝试用 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
因此您可以使用 .toSet
将您的“集合”转换为实际集合,并使用它
关于scala - 如何在 Scala 中实现 Python 的 issuperset(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39229727/