给Python程序员的Scala入门教程
转载自:https://www.jianshu.com/p/59dbb62ab358
快速语法对照
List
|
Python |
Scala |
---|
空List |
a = [] |
val a = List() //List[Nothing] |
Int |
a = [1,2,3,4,5] |
val a = List(1,2,3,4,5) |
String |
a = ["a", "b"] |
val a: List[String] = List("Hello", "World") |
不同类型 |
a = [1,"Hello"] |
val a = List(1, "Hello") //List[Any] |
2维 |
a = [[1,2,3], [4,5,6]] |
val a = List(List(1,2,3), List(4,5,6)) |
索引 |
a[10] |
a(10) |
截取 |
a[0:2] |
a.slice(0,2) |
是否为空 |
not a a==[] len(a)==0 |
a.isEmpty |
append |
a.append(6) |
a :+ 6 |
连接 |
a.extend([4,5,6]) |
List.concat(List(1,2,3), List(4,5,6)) |
反转 |
a[::-1] |
a.reverse |
HashMap
|
Python |
Scala |
---|
新建 |
map = {"one": 1, "two":2} |
val map = Map("one"->1, "two"->2) |
新建 |
|
val map = Map(("one", 1), ("two", 2)) |
获取 |
map["one"] |
map("one") |
包含 |
"one" in map |
map.contains("one") |
添加 |
map["three"] = 3 |
map + ("three"->3) |
删除 |
del map["three"] |
map - "three" |
keys |
map.keys() |
map.keys |
values |
map.values() |
map.values |
concat |
map1.update(map2) |
map1 ++ map2 |
Set
|
Python |
Scala |
---|
新建 |
s = {1,2,3} |
val s = Set(1,2,3) |
新建 |
s = set([1,2,3]) |
|
添加 |
s.add(4) |
s + 4 |
删除 |
s.remove(4) |
s - 4 |
是否为空 |
nor s |
s.isEmpty |
min |
min(s) |
s.min |
max |
max(s) |
s.max |
concat |
s1.union(s2) |
s1.union(s2) |
concat |
|
s1 ++ s2 |
For loop
|
Python |
Scala |
---|
Range |
for x in range(5): print(x) |
for(x <- Range(1, 5)) println(x) |
List |
for x in li: print(x) |
for (x <- li) println(x) |
Map |
for k, v in map1.items(): print(k,v) |
for ((k,v) <- map1) println(k, v) |
Range
Python |
Scala |
---|
range(1, 10) (inclusive, exclusive) |
Range(1, 10) (inclusive, exclusive) |
|
1 to 10 (inclusive, inclusive) |
|
1 until 10 (inclusive, exclusive) |
range(10) (exclusive) |
|
range(1, 10, 2) |
1 to 10 by 2 |
仅支持int |
1.0 to 10.0 by 0.5 |
仅支持int |
'a' to 'g' by 2 |