Python學習之如何簡化程式碼?六大技巧!

老男孩IT教育機構發表於2021-01-06

  眾所周知,對比其他程式語言,Python更加簡潔優雅、語法清晰,可以實現龐大的功能,那麼Python開發如何簡化程式碼呢?我們一起來看看方法吧。

  1. 列表推導式

  對於一組列表,如果想讓其所有元素翻倍,很多人都會採用以往比較經典的寫法,其實Python中有更精簡的辦法,例項如下:

  以往做法:

  num = [1, 3, 5, 7, 9]

  for i in range(len(num)):

  num[i] = num[i] * 3

  Python簡化寫法:

  num = [1, 3, 5, 7, 9]

  bag = [elem * 3 for elem in num]

  2. 遍歷列表

  傳統遍歷列表是用函式表示列表的長度進行迴圈遍歷,Python3可以省略這一步,更加簡潔!

  以往做法:

  num = [1, 3, 5, 7, 9]

  for i in range(len(num)):

  print(num[i])

  Python簡化寫法:

  num = [1, 3, 5, 7, 9]

  for i in num:

  print(i)

  3. 元素互換

  對於元素互換,傳統做法需要設定一箇中間變數,進行數值的承接,Python元素互換變得簡單了很多。

  以往做法:

  a = 3

  b = 4

  c = a

  a = b

  b = c

  Python簡化寫法:

  a = 3

  b = 4

  a,b = b,a

  4. 初始化列表

  Python也有簡潔的初始化列表表示方法,具體簡潔程度,舉個例子感受一下吧,以下是要一個是8個整數1的列表

  以往做法:

  bag = []

  for _ in range(8):

  bag.append(1)

  Python簡化寫法:

  bag = [1] * 8

  5. 構造字串

  經常列印字串,需要用到建構函式,傳統寫法需要很多連線符和引數比較複雜,Python用法就簡潔很多,以下是相關例項:

  以往做法:

  name = “oldboy”

  age = “30”

  born_in = “beijing”

  str = "Hello my name is " + name + "and I'm " + str(age) + " years old. I was born in " + born_in + "."

  print(str)

  Python簡化寫法:

  name = “oldboy”

  age = “30”

  born_in = “beijing”

  str = "Hello my name is {0} and I'm {1} years old. I was born in {2}.".format(name, age, born_in)

  print(str)

  6.返回tuples元組

  Python允許一個函式中返回多個元素,以下是解包元組例項:

  以往做法:

  def binary():

  return 0, 1

  result = binary()

  zero = result[0]

  >

  Python簡化寫法:

  def binary():

  return 0, 1

  zero, >


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69952527/viewspace-2747979/,如需轉載,請註明出處,否則將追究法律責任。

相關文章