楼主: ReneeBK
1730 4

【GitHub】Python to Scala [推广有奖]

  • 1关注
  • 62粉丝

VIP

学术权威

14%

还不是VIP/贵宾

-

TA的文库  其他...

R资源总汇

Panel Data Analysis

Experimental Design

威望
1
论坛币
49407 个
通用积分
51.8104
学术水平
370 点
热心指数
273 点
信用等级
335 点
经验
57815 点
帖子
4006
精华
21
在线时间
582 小时
注册时间
2005-5-8
最后登录
2023-11-26

相似文件 换一批

+2 论坛币
k人 参与回答

经管之家送您一份

应届毕业生专属福利!

求职就业群
赵安豆老师微信:zhaoandou666

经管之家联合CDA

送您一个全额奖学金名额~ !

感谢您参与论坛问题回答

经管之家送您两个论坛币!

+2 论坛币

本帖隐藏的内容

python-to-scala.pdf (385.99 KB)


  1. The goal of this project is to be a concise guide for those transitioning from Python to Scala. This is by no means meant to be a complete guide to Scala, but rather some (hopefully) helpful snippets of code to help you translate between the two languages.

  2. This guide loosely follows along with the text of Scala for the Impatient, a great introductory book for those learning Scala. You might find it helpful to read it alongside the chapters from this repo.

  3. Note that in general, you should not try to directly translate idioms from one language to another; you don't want to write Scala that looks like Python- you want to write Scala that looks like Scala! You should strive to write idiomatic code whenever possible. A good starting point is Twitter's Effective Scala

  4. I recommend reading through the guide in the following order:
  5. 1.Variables and Arithmetic
  6. 2.Conditionals
  7. 3.Functions
  8. 4.Strings
  9. 5.Arrays
  10. 6.Maps
  11. 7.Tuples
  12. 8.Exceptions
  13. 9.Classes

  14. Here are some Scala topics not discussed above that I think are important to review:
  15. •Pattern Matching This is like a switch statement on turbo, and is very powerful and oft used. The Scala Cookbook has really great practical examples.
  16. •Auxiliary Constructors Classes can have multiple constructors that operate on different argument types/number of args.
  17. •Case Classes as an immutable, record-like data-structure that can be pattern-matched.
  18. •Scala Collections There is a lot of power in all of the methods available to data structures like Vector, Array, List, Sequence, Set, etc. Just take a look at all of the available methods.

  19. All of the code for this book can be found on Github.
复制代码


二维码

扫码加我 拉你入群

请注明:姓名-公司-职位

以便审核进群资格,未注明则拒绝

关键词:GitHub python SCALA Hub hide

本帖被以下文库推荐

沙发
ReneeBK 发表于 2017-2-21 07:03:54 |只看作者 |坛友微信交流群
  1. Variables

  2. This is going to be a very quick review, as there shouldn't be much surprising with the way Scala handles values (immutable) and variables (mutable):

  3. Python:
  4. >>> foo = "Apples"
  5. >>> baz = foo + " and Oranges."
  6. >>> baz
  7. 'Apples and Oranges.'
  8. >>> baz = "Only Grapes."


  9. Scala:
  10. scala> val foo = "Apples"
  11. foo: String = Apples

  12. scala> val baz = foo + " and Oranges."
  13. baz: String = Apples and Oranges.


  14. scala> baz
  15. res60: String = Apples and Oranges.


  16. // In Scala, vals are immutable
  17. scala> baz = "Only Grapes."
  18. <console>:13: error: reassignment to val
  19.        baz = "Only Grapes."


  20. // Create a var instead
  21. scala> var baz = "Apples and Oranges."
  22. baz: String = Apples and Oranges.

  23. scala> baz = "Only Grapes."
  24. baz: String = Only Grapes.

  25. scala> var one = 1
  26. one: Int = 1

  27. scala> one += 1

  28. scala> one
  29. res21: Int = 2


  30. Scala will also allow you to more strongly type your variables, rather than letting the compiler interpret the type:

  31. Scala
  32. scala> val foo: String = "Apples"
  33. foo: String = Apples


  34. Python and Scala will both let you perform multiple assignment. However, be careful with Python and pass by reference! You'll usually want to unpack rather than perform multiple assignment.

  35. Scala:
  36. scala> val foo, bar = Array(1, 2, 3)
  37. foo: Array[Int] = Array(1, 2, 3)
  38. bar: Array[Int] = Array(1, 2, 3)

  39. // foo and bar reference different pieces of memory; changing one will not change the other.
  40. scala> bar(0) = 4

  41. scala> bar
  42. res70: Array[Int] = Array(4, 2, 3)

  43. scala> foo
  44. res71: Array[Int] = Array(1, 2, 3)


  45. The same can be achieved with Python unpacking:
  46. >>> foo, bar = [1, 2, 3], [1, 2, 3]
  47. # Are they referencing the same memory?
  48. >>> foo is bar
  49. False
  50. # What happens when you change bar?
  51. >>> bar[0] = 4
  52. >>> bar
  53. [4, 2, 3]
  54. >>> foo
  55. [1, 2, 3]


  56. # You *can* assign both foo and bar the same value, but they reference the same memory!
  57. >>> foo = bar = [1, 2, 3]
  58. >>> foo is bar
  59. True
  60. >>> bar[0] = 4
  61. >>> bar
  62. [4, 2, 3]
  63. >>> foo
  64. [4, 2, 3]


  65. Scala and Python largely share arithmetic operations. Behind the scenes, they are both using methods to implement the operaters- Scala uses the actual operator symbol, rather than an alphanumeric character:

  66. Python
  67. >>> foo = 1
  68. # What's happening behind the scenes?
  69. >>> foo.__add__(4)
  70. 5


  71. Scala
  72. scala> val foo = 1
  73. foo: Int = 1

  74. scala> foo + 1
  75. res72: Int = 2
  76. // What's happening behind the scenes:
  77. scala> foo.+(1)
  78. res73: Int = 2
复制代码

使用道具

藤椅
ReneeBK 发表于 2017-2-21 07:06:07 |只看作者 |坛友微信交流群
  1. Conditional Expressions

  2. Scala's if/else/else-if will look very familiar to those who have written in C-style languages before:

  3. Python
  4. >>> x = 0
  5. # Inline: expression_if_true if condition else expression_if_false
  6. >>> foo = 1 if x > 0 else -1
  7. >>> foo
  8. -1
  9. # Expressions broken across multiple lines
  10. if x == 1:
  11.     foo = 5
  12. elif x == 0:
  13.     foo = 6
  14. >>> foo
  15. 6
  16. >>>
  17. if isinstance('foo', str):
  18.     print('Foo is string')
  19. else:
  20.     print('Foo is not string')

  21. Foo is string


  22. Scala
  23. scala> val x = 0
  24. x: Int = 0

  25. // Inline: variable assignment expression
  26. scala> val foo = if (x > 0) 1 else -1
  27. foo: Int = -1

  28. scala> var baz = 1
  29. baz: Int = 1

  30. // REPL paste mode
  31. scala> :paste
  32. // Entering paste mode (ctrl-D to finish)
  33. // Kernighan & Ritchie brace style preferred for multi-line expressions
  34. if (x == 0) {
  35.   baz = 5
  36. }
  37. // Exiting paste mode, now interpreting.

  38. scala> baz
  39. res90: Int = 5
  40. // But for simple expressions, try to keep them to one line
  41. scala> if (x == 0) baz = 6

  42. scala> baz
  43. res94: Int = 6

  44. scala>

  45. if (foo.isInstanceOf[String]) {
  46.     print("Foo is a string!")
  47. } else if (foo.isInstanceOf[Int]) {
  48.     print("Foo is an int!")
  49. } else {
  50.     print("I dont know what foo is...")
  51. }

  52. Foo is a string!


  53. While loops should look familiar as well:

  54. Python
  55. n = 0
  56. nlist = []
  57. while n < 5:
  58.     nlist.append(n)
  59.     n += 1
  60. >>> nlist
  61. [0, 1, 2, 3, 4]


  62. The following can actually be handled much better with a comprehension and a more functional approach, discussed below:

  63. Scala
  64. n: Int = 0

  65. // ArrayBuffer is a mutable array that acts like Python lists.
  66. scala> import scala.collection.mutable.ArrayBuffer
  67. import scala.collection.mutable.ArrayBuffer

  68. scala> var nlist = ArrayBuffer[Int]()
  69. nlist: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer()

  70. scala>

  71. while (n < 5) {
  72.     nlist += n
  73.     n += 1
  74. }

  75. scala> nlist
  76. res115: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(0, 1, 2, 3, 4)
  77. }


  78. For-loops and comprehensions, the latter of which is likely sorely missed by Python programmers writing Java. Scala supports a  for (variable <- expression)  syntax. Let's look at Python first:

  79. Python
  80. foo = "Apple"
  81. n = 0
  82. for a in foo:
  83.     n += 1
  84. >>> n
  85. 5


  86. Scala
  87. scala> val foo = "Apple"

  88. scala> var n = 0

  89. scala>
  90. for (x <- foo) {
  91.     n += 1
  92. }

  93. scala> n
  94. res140: n: Int = 5

  95. // This would actually be better expressed in a single line
  96. scala> n = 0

  97. scala> for (x <- foo) n += 1

  98. scala> n
  99. res141: n: Int = 5


  100. Python comprehensions are a very important part of writing idiomatic Python; Scala supports the same with the yield syntax:

  101. Python
  102. >>> [f + 1 for f in [1, 2, 3, 4, 5]]
  103. [2, 3, 4, 5, 6]


  104. Scala
  105. scala> for (f <- Array(1, 2, 3, 4, 5)) yield f + 1
  106. res59: Array[Int] = Array(2, 3, 4, 5, 6)


  107. Python has a very useful function called  zip  that will allow you to iterate over iterables at the same time. Scala will allow you to have multiple "generators" in an expression, which can replicate the zip behavior:

  108. Python
  109. foo, bar = [1, 2, 3], ['a', 'b', 'c']
  110. foobars = {}
  111. for f, b in zip(foo, bar):
  112.     foobars[b] = f
  113. >>> foobars
  114. {'a': 1, 'c': 3, 'b': 2}

  115. # It's more Pythonic to use a comprehension
  116. >>> {b: f for f, b in zip(foo, bar)}
  117. {'a': 1, 'c': 3, 'b': 2}


  118. Scala
  119. val foo = Array(1, 2, 3)
  120. val bar = Array("a", "b", "c")

  121. import scala.collection.mutable.Map
  122. // Let's go ahead and specify the types, since we know them
  123. var foobars= Map[String, Int]()

  124. for (f <- foo; b <- bar) foobars += (b -> f)
  125. scala> foobars
  126. res5: scala.collection.mutable.Map[String,Int] = Map(b -> 3, a -> 3, c -> 3)

  127. // This is really powerful- we're not limited to two iterables
  128. val baz = Array("apple", "orange", "banana")
  129. val mapped = Map[String, (Int, String)]()
  130. for (f <- foo; b <- bar; z <- baz) mapped += (z -> (f, b))
  131. scala> mapped
  132. res7: scala.collection.mutable.Map[String,(Int, String)] = Map(banana -> (3,c), orange -> (3,c), apple -> (3,c))

  133. // It's worth noting that Scala also has an explicit zip method
  134. val arr1 = Array(1, 2, 3)
  135. val arr2 = Array(4, 5, 6)

  136. scala> arr1.zip(arr2)
  137. res240: Array[(Int, Int)] = Array((1,4), (2,5), (3,6))


  138. Python's enumerate is a really nice language feature, and is mirrored by Scala's  zipWithIndex :

  139. Python
  140. >>> [(x, y) for x, y in enumerate(["foo", "bar", "baz"])]
  141. [(0, 'foo'), (1, 'bar'), (2, 'baz')]


  142. Scala
  143. scala> for ((y, x) <- Array("foo", "bar", "baz").zipWithIndex) yield (x, y)
  144. res27: Array[(Int, String)] = Array((0,foo), (1,bar), (2,baz))

  145. // Note that simply calling zipWithIndex will return something similar (but with values // in reverse order)
  146. scala> Array("foo", "bar", "baz").zipWithIndex
  147. res31: Array[(String, Int)] = Array((foo,0), (bar,1), (baz,2))


  148. Scala will allow "guard" expressions, which is the same as a control flow expression in Python:

  149. Python
  150. foo = [1,2,3,4,5]
  151. bar = [x for x in foo if x != 3]
  152. >>> bar
  153. [1, 2, 4, 5]


  154. Scala
  155. val foo = Array(1, 2, 3, 4, 5)
  156. var bar = ArrayBuffer[Int]()
  157. for (f <- foo if f != 3) bar += f
  158. scala> bar
  159. res136: scala.collection.mutable.ArrayBuffer[Int] = ArrayBuffer(1, 2)

  160. // You can stack guards
  161. scala> for (x <- (1 to 5).toArray if x != 2 if x != 3) yield x
  162. res44: Array[Int] = Array(1, 4, 5)


  163. Note that in many cases, it may be more concise to use  map  vs a for-comprehension:

  164. Scala
  165. scala> for (c <- Array(1, 2, 3)) yield c + 2
  166. res56: Array[Int] = Array(3, 4, 5)

  167. scala> Array(1, 2, 3).map(_ + 2)
  168. res57: Array[Int] = Array(3, 4, 5)
复制代码

使用道具

板凳
smartlife 在职认证  发表于 2017-2-21 11:21:30 |只看作者 |坛友微信交流群
已有 1 人评分论坛币 收起 理由
Nicolle + 20 鼓励积极发帖讨论

总评分: 论坛币 + 20   查看全部评分

使用道具

报纸
LudwigEisberg 发表于 2023-7-17 10:14:43 |只看作者 |坛友微信交流群
谢谢楼主分享

使用道具

您需要登录后才可以回帖 登录 | 我要注册

本版微信群
加JingGuanBbs
拉您进交流群

京ICP备16021002-2号 京B2-20170662号 京公网安备 11010802022788号 论坛法律顾问:王进律师 知识产权保护声明   免责及隐私声明

GMT+8, 2024-4-25 21:15