Python和Scala的语法对照表(持续更新中)

Lambda

  Python Scala
传入多个参数 a = lambda x,y,z:(x+8)*y-z
print(a(5,6,8))
 
 
lambda表达式后面传参 (lambda x, y: x if x>y else y)(1, 2)  

lambda函数本身做为return的值

def add(n):
    return lambda x: x+n
f = add(1)
print(f(2))
 
列表结合使用

L = [lambda x: x**2,\
     lambda x: x**3,\
     lambda x: x**4]
for x in L:
        print(x(2))


print("------------------------------")
print(L[0](2))

 
字典配合使用 key = 'B'
dic = { 'A': lambda: 2*2,\
        'B': lambda: 2*4,\
        'C': lambda: 2*6}
print(dic[key]())
 
结合map函数使用 squares = map(lambda x: x**2, range(5))
print(list(squares))
 
结合reduce函数使用 from functools import reduce
def add(x, y) : # 两数相加
    return x + y
print(reduce(add, [1,2,3,4,5]))
print(reduce(lambda x, y: x+y, [1,2,3,4,5]))
 
结合filter函数使用 print(list(filter(lambda x: x%2==0,  [1,2,3,4,5,6])))  
结合sorted函数使用 info = [('James',32), ('Alies',20), ('Wendy',25)]
print(sorted(info, key=lambda age:age[1]))# 按照第二个元素,索引为1排序
 
要点

①lambda 函数不能包含命令,

②包含的表达式不能超过一个。

③lambda 并不会带来程序运行效率的提高,只会使代码更简洁。

 

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

列表推导式

Python Scala
dogBreeds =["Doberman", "Yorkshire Terrier", "Dachshund","Scottish Terrier", "Great Dane","Portuguese Water Dog"]
filteredBreeds=[breed for breed in dogBreeds if "Terrier" in breed and not breed.startswith('Yorkshire')]
print(filteredBreeds)
 
val dogBreeds = List("Doberman", "Yorkshire Terrier", "Dachshund","Scottish Terrier", "Great Dane","Portuguese Water Dog")
val filteredBreeds = for {breed <- dogBreeds if breed.contains("Terrier") && !breed.startsWith("Yorkshire")} yield breed
println(filteredBreeds)

Main函数写法

Python Scala

def main():
    print("hello world")


if __name__ == '__main__':
    main()

object HelloWorld{ def main(args : Array[String]){ println("HelloWorld") } }

迭代器

Python Scala

import sys         # 引入 sys 模块
list=["Baidu", "Google", "Runoob", "Taobao"]
it = iter(list)    # 创建迭代器对象
 
while True:
    try:
        print (next(it))
    except StopIteration:

object Test {
   def main(args: Array[String]) {
      val it = Iterator("Baidu", "Google", "Runoob", "Taobao")
      
      while (it.hasNext){
         println(it.next())
      }
   }
}

生成器


Reference:
[1]给Python程序员的Scala入门教程

[2]Scala学习日志(三)——轻便神奇的for推导式

[3]python中lambda的用法

[4]Scala编程 Lambda Expressions

[5]scala中的Lambda表达式

猜你喜欢

转载自blog.csdn.net/appleyuchi/article/details/107693958