scala中创建时间序列_如何从Scala中的序列中提取唯一元素?
scala中創建時間序列
While storing data elements to a data structure or extracting raw data duplicate data might be included and this data decreases the efficiency of the code. So, eliminating duplicate data or extracting unique elements is important.
在將數據元素存儲到數據結構或提取原始數據時,可能會包含重復數據,并且此數據會降低代碼的效率。 因此,消除重復數據或提取唯一元素很重要。
We can extract unique elements from sequences in Scala using two methods,
我們可以使用兩種方法從Scala中的序列中提取唯一元素 ,
1)使用獨特的方法 (1) Using distinct method)
The distinct method is used to extract unique elements from a collection.
獨特的方法用于從集合中提取唯一元素。
Syntax:
句法:
collection_name.distinctThe method returns a collection with unique elements only.
該方法僅返回具有唯一元素的集合。
Program to extract unique elements using distinct method
程序使用獨特的方法提取獨特的元素
object MyClass {def main(args: Array[String]) {val seq = Array(10, 20, 80, 10, 50, 10)printf("Elements of the Array: ")for(i <- 0 to seq.length-1)print(seq(i)+" ")println()val uniqueSeq = seq.distinctprintf("The unique elements are: ")for(i <- 0 to uniqueSeq.length-1)print(uniqueSeq(i)+" ")println()} }Output:
輸出:
Elements of the Array: 10 20 80 10 50 10 The unique elements are: 10 20 80 502)使用toSet方法 (2) Using toSet method)
One more promising solution to the problem is converting the sequence to set. As the set is a collection of all unique elements only all the duplicate elements will be deleted.
解決該問題的另一種有希望的解決方案是將序列轉換為set。 由于集合是所有唯一元素的集合,因此僅所有重復元素將被刪除。
Syntax:
句法:
sequence.toSetThe method returns a set with all unique elements.
該方法返回具有所有唯一元素的集合。
Program to extract unique elements using set conversion method
程序使用集合轉換方法提取唯一元素
object myObject {def main(args: Array[String]) {val seq = Array(10, 20, 80, 10, 50, 10)printf("Elements of the Array: ")for(i <- 0 to seq.length-1)print(seq(i)+" ")println()val set = seq.toSetprint("Elements of the Array when converted to set: ")print(set)} }Output:
輸出:
Elements of the Array: 10 20 80 10 50 10 Elements of the Array when converted to set: Set(10, 20, 80, 50)翻譯自: https://www.includehelp.com/scala/how-to-extract-unique-elements-from-sequences-in-scala.aspx
scala中創建時間序列
總結
以上是生活随笔為你收集整理的scala中创建时间序列_如何从Scala中的序列中提取唯一元素?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 带有Python示例的math.cos(
- 下一篇: 如何给SpringBoot配置轻松加密?