scala zip 拉鍊操作入門

2021-10-10 12:00:10 字數 2539 閱讀 8157

zip主要用於關聯兩個集合,關聯的結果可以是array,list等等,然後集合中的元素成為二元tuple

//建立乙個array

scala>

var names=array(

"zhangsan"

,"lisi"

,"wangmazi"

)names: array[

string

]= array(zhangsan, lisi, wangmazi)

//建立另乙個array scores

scala>

val scores=array(60,

70,90)

scores: array[

int]

= array(60,

70,90)

//利用zip關聯兩個array,形成乙個新的array,array中的每個元素是乙個tuple,詳見tuple

scala> names.zip(scores)

res0: array[

(string

,int)]

= array(

(zhangsan,60)

,(lisi,70)

,(wangmazi,90)

)//zip關聯的另一種寫法

scala> names zip scores

res1: array[

(string

,int)]

= array(

(zhangsan,60)

,(lisi,70)

,(wangmazi,90)

)//建立乙個seq

scala>

val nums=seq(0,

1,2,

3,4)

nums: seq[

int]

= list(0,

1,2,

3,4)

//建立乙個list

scala>

val series=list(

"a",

"b",

"c")

series: list[

string

]= list(a, b, c)

//關聯2個list和seq,任意集合均可關聯,集合長度不一樣時候以短的為準

scala> nums.zip(series)

res5: seq[

(int

,string)]

= list((0

,a),(1

,b),(2

,c))

//關聯也有主動被動的問題

scala> series.zip(nums)

res6: list[

(string

,int)]

= list(

(a,0),

(b,1),

(c,2))

//關聯集合長度不一樣時可以用預設值處理.

scala> nums.zipall(series,

"a",20)

res7: seq[

(any

,any)]

= list((0

,a),(1

,b),(2

,c),(3

,20),

(4,20

))scala> series.zipall(nums,

"a",20)

res8: list[

(string

,int)]

= list(

(a,0),

(b,1),

(c,2),

(a,3),

(a,4))

scala> series

res9: list[

string

]= list(a, b, c)

//關聯索引和元素自身

scala> series.zipwithindex

res10: list[

(string

,int)]

= list(

(a,0),

(b,1),

(c,2))

//關聯時自定義索引的起始位置

scala>

val ps=series.zip(stream from 10

)ps: list[

(string

,int)]

= list(

(a,10),

(b,11),

(c,12))

//如果想解除關聯,恢復自由身

scala> ps unzip

warning: there was one feature warning; re-run with

-feature for details

res12:

(list[

string

], list[

int])=

(list(a, b, c)

,list(10,

11,12)

)

scala元組及拉鍊操作

scala元組及拉鍊操作 scala裡面的元組是可是不同資料型別的 scala scala 1 res45 string,int scala,1 scala val t scala 100l,3.14,spark 1 t string,long,double,string,int scala,100...

雜湊表的基本操作 拉鍊法

hashtablebucket.h pragma once include include include include include typedef char htbkeytype typedef char htbvaluetype typedef char htbkeytype typede...

雜湊桶的各操作總結 拉鍊法

0.定義結構 雜湊表中結點的型別 拉鍊法 typedef struct hashnode hashnode 雜湊表的型別 typedef struct hashtablebucket htb 1.介面宣告 初始化 void htbinit htb htb,size t len 銷毀雜湊表 void ...