乡下人产国偷v产偷v自拍,国产午夜片在线观看,婷婷成人亚洲综合国产麻豆,久久综合给合久久狠狠狠9

  • <output id="e9wm2"></output>
    <s id="e9wm2"><nobr id="e9wm2"><ins id="e9wm2"></ins></nobr></s>

    • 分享

      超實(shí)用的 30 段Python 案例(下)

       Yy3318q 2021-12-08

      Python是目前最流行的語言之一,它在數(shù)據(jù)科學(xué)、機(jī)器學(xué)習(xí)、web開發(fā)、腳本編寫、自動(dòng)化方面被許多人廣泛使用。

      它的簡(jiǎn)單和易用性造就了它如此流行的原因。

      如果你正在閱讀本文,那么你或多或少已經(jīng)使用過Python或者對(duì)Python感興趣。

      在本文中,我們將會(huì)介紹 30 個(gè)簡(jiǎn)短的代碼片段,你可以在 30 秒或更短的時(shí)間里理解和學(xué)習(xí)這些代碼片段。

      接上篇:超實(shí)用的 30 段 Python 案例(上)

      16.尋找差異

      下面的方法在將給定的函數(shù)應(yīng)用于兩個(gè)列表的每個(gè)元素后,返回兩個(gè)列表之間的差值。

      def difference_by(a, b, fn):
      b = set(map(fn, b))
      return [item for item in a if fn(item) not in b]
      from math import floor
      difference_by([2.1, 1.2], [2.3, 3.4],floor) # [1.2]
      difference_by([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], lambda v : v['x']) # [ { x: 2 } ]

      17.鏈?zhǔn)胶瘮?shù)調(diào)用

      以下方法可在一行中調(diào)用多個(gè)函數(shù)。

      def add(a, b):
      return a + b
      def subtract(a, b):
      return a - b
      a, b = 4, 5
      print((subtract if a > b else add)(a, b)) # 9

      18.檢查重復(fù)值

      以下方法使用 set() 方法僅包含唯一元素的事實(shí)來檢查列表是否具有重復(fù)值。

      def has_duplicates(lst):
      return len(lst) != len(set(lst))

      x = [1,2,3,4,5,5]
      y = [1,2,3,4,5]
      has_duplicates(x) # True
      has_duplicates(y) # False

      19.合并兩個(gè)詞典

      以下方法可用于合并兩個(gè)詞典。

      def merge_two_dicts(a, b):
      c = a.copy() # make a copy of a
      c.update(b) # modify keys and values of a with the ones from b
      return c
      a = { 'x': 1, 'y': 2}
      b = { 'y': 3, 'z': 4}
      print(merge_two_dicts(a, b)) # {'y': 3, 'x': 1, 'z': 4}

      在Python 3.5及更高版本中,你還可以執(zhí)行以下操作:

      def merge_dictionaries(a, b)
      return {**a, **b}
      a = { 'x': 1, 'y': 2}
      b = { 'y': 3, 'z': 4}
      print(merge_dictionaries(a, b)) # {'y': 3, 'x': 1, 'z': 4}

      20.將兩個(gè)列表轉(zhuǎn)換成一個(gè)詞典

      以下方法可將兩個(gè)列表轉(zhuǎn)換成一個(gè)詞典。

      def to_dictionary(keys, values):
      return dict(zip(keys, values))

      keys = ['a', 'b', 'c']
      values = [2, 3, 4]
      print(to_dictionary(keys, values)) # {'a': 2, 'c': 4, 'b': 3}

      21.使用枚舉

      以下方法將字典作為輸入,然后僅返回該字典中的鍵。

      list = ['a', 'b', 'c', 'd']
      for index, element in enumerate(list):
      print('Value', element, 'Index ', index, )
      # ('Value', 'a', 'Index ', 0)
      # ('Value', 'b', 'Index ', 1)
      #('Value', 'c', 'Index ', 2)
      # ('Value', 'd', 'Index ', 3)

      22.計(jì)算所需時(shí)間

      以下代碼段可用于計(jì)算執(zhí)行特定代碼所需的時(shí)間。

      import time
      start_time = time.time()
      a = 1
      b = 2
      c = a + b
      print(c) #3
      end_time = time.time()
      total_time = end_time - start_time
      print('Time: ', total_time)
      # ('Time: ', 1.1205673217773438e-05)

      23.Try else 指令

      你可以將 else 子句作為 try/except 塊的一部分,如果沒有拋出異常,則執(zhí)行該子句。

      try:
      2*3
      except TypeError:
      print('An exception was raised')
      else:
      print('Thank God, no exceptions were raised.')
      #Thank God, no exceptions were raised.

      24.查找最常見元素

      以下方法返回列表中出現(xiàn)的最常見元素。

      def most_frequent(list):
      return max(set(list), key = list.count)

      list = [1,2,1,2,3,2,1,4,2]
      most_frequent(list)

      25.回文

      以下方法可檢查給定的字符串是否為回文結(jié)構(gòu)。該方法首先將字符串轉(zhuǎn)換為小寫,然后從中刪除非字母數(shù)字字符。最后,它會(huì)將新的字符串與反轉(zhuǎn)版本進(jìn)行比較。

      def palindrome(string):
      from re import sub
      s = sub('[W_]', '', string.lower())
      return s == s[::-1]
      palindrome('taco cat') # True

      26.沒有 if-else 語句的簡(jiǎn)單計(jì)算器

      以下代碼段將展示如何編寫一個(gè)不使用 if-else 條件的簡(jiǎn)單計(jì)算器。

      import operator
      action = {
      '+': operator.add,
      '-': operator.sub,
      '/': operator.truediv,
      '*': operator.mul,
      '**': pow
      }
      print(action['-'](50, 25)) # 25

      27.元素順序打亂

      以下算法通過實(shí)現(xiàn) Fisher-Yates算法 在新列表中進(jìn)行排序來將列表中的元素順序隨機(jī)打亂。

      from copy import deepcopy
      from random import randint
      def shuffle(lst):
      temp_lst = deepcopy(lst)
      m = len(temp_lst)
      while (m):
      m -= 1
      i = randint(0, m)
      temp_lst[m], temp_lst[i] = temp_lst[i], temp_lst[m]
      return temp_lst

      foo = [1,2,3]
      shuffle(foo) # [2,3,1] , foo = [1,2,3]

      28.列表扁平化

      以下方法可使列表扁平化,類似于JavaScript中的[].concat(…arr)。

      def spread(arg):
      ret = []
      for i in arg:
      if isinstance(i, list):
      ret.extend(i)
      else:
      ret.append(i)
      return ret
      spread([1,2,3,[4,5,6],[7],8,9]) # [1,2,3,4,5,6,7,8,9]

      29.變量交換

      以下是交換兩個(gè)變量的快速方法,而且無需使用額外的變量。

      def swap(a, b):
      return b, a
      a, b = -1, 14
      swap(a, b) # (14, -1)

      30.獲取缺失鍵的默認(rèn)值

      以下代碼段顯示了如何在字典中沒有包含要查找的鍵的情況下獲得默認(rèn)值。

      d = {'a': 1, 'b': 2}
      print(d.get('c', 3)) # 3

       接上篇:超實(shí)用的 30 段 Python 案例(上)

      關(guān)注作者新號(hào):web前端營 獲取海量IT類教程

      都來到這了,拜托拜托關(guān)注下

       

      點(diǎn)贊在看就是最大的支持??

        本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
        轉(zhuǎn)藏 分享 獻(xiàn)花(0

        0條評(píng)論

        發(fā)表

        請(qǐng)遵守用戶 評(píng)論公約

        類似文章 更多