<kbd id="afajh"><form id="afajh"></form></kbd>
<strong id="afajh"><dl id="afajh"></dl></strong>
    <del id="afajh"><form id="afajh"></form></del>
        1. <th id="afajh"><progress id="afajh"></progress></th>
          <b id="afajh"><abbr id="afajh"></abbr></b>
          <th id="afajh"><progress id="afajh"></progress></th>

          【Python】13 個(gè)非常有用的 Python 代碼片段,建議收藏!

          共 9536字,需瀏覽 20分鐘

           ·

          2022-07-04 20:01

          今天我們主要來介紹應(yīng)用程序當(dāng)中的通用 Python 代碼片段,一起進(jìn)步吧

          Lists Snippets

          我們先從最常用的數(shù)據(jù)結(jié)構(gòu)列表開始

          №1:將兩個(gè)列表合并成一個(gè)字典

          假設(shè)我們?cè)?Python 中有兩個(gè)列表,我們希望將它們合并為字典形式,其中一個(gè)列表的項(xiàng)作為字典的鍵,另一個(gè)作為值。這是在用 Python 編寫代碼時(shí)經(jīng)常遇到的一個(gè)非常常見的問題

          但是為了解決這個(gè)問題,我們需要考慮幾個(gè)限制,比如兩個(gè)列表的大小,兩個(gè)列表中元素的類型,以及其中是否有重復(fù)的元素,尤其是我們將使用的元素作為 key 時(shí)。我們可以通過使用 zip 等內(nèi)置函數(shù)來解決這些問題

          keys_list = ['A''B''C']
          values_list = ['blue''red''bold']

          #There are 3 ways to convert these two lists into a dictionary
          #1- Using Python's zip, dict functionz
          dict_method_1 = dict(zip(keys_list, values_list))

          #2- Using the zip function with dictionary comprehensions
          dict_method_2 = {key:value for key, value in zip(keys_list, values_list)}

          #3- Using the zip function with a loop
          items_tuples = zip(keys_list, values_list) 
          dict_method_3 = {} 
          for key, value in items_tuples: 
              if key in dict_method_3: 
                  pass # To avoid repeating keys.
              else
                  dict_method_3[key] = value

          №2:將兩個(gè)或多個(gè)列表合并為一個(gè)包含列表的列表

          另一個(gè)常見的任務(wù)是當(dāng)我們有兩個(gè)或更多列表時(shí),我們希望將它們?nèi)渴占揭粋€(gè)大列表中,其中較小列表的所有第一項(xiàng)構(gòu)成較大列表中的第一個(gè)列表

          例如,如果我們有 4 個(gè)列表 [1,2,3], ['a','b','c'], ['h','e','y'] 和 [4,5, 6],我們想為這四個(gè)列表創(chuàng)建一個(gè)新列表;它將是 [[1,'a','h',4], [2,'b','e',5], [3,'c','y',6]]

          def merge(*args, missing_val = None):
          #missing_val will be used when one of the smaller lists is shorter tham the others.
          #Get the maximum length within the smaller lists.
            max_length = max([len(lst) for lst in args])
            outList = []
            for i in range(max_length):
              result.append([args[k][i] if i < len(args[k]) else missing_val for k in range(len(args))])
            return outList

          №3:對(duì)字典列表進(jìn)行排序

          這一組日常列表任務(wù)是排序任務(wù),根據(jù)列表中包含的元素的數(shù)據(jù)類型,我們將采用稍微不同的方式對(duì)它們進(jìn)行排序。

          dicts_lists = [
            {
              "Name""James",
              "Age"20,
            },
            {
               "Name""May",
               "Age"14,
            },
            {
              "Name""Katy",
              "Age"23,
            }
          ]

          #There are different ways to sort that list
          #1- Using the sort/ sorted function based on the age
          dicts_lists.sort(key=lambda item: item.get("Age"))

          #2- Using itemgetter module based on name
          from operator import itemgetter
          f = itemgetter('Name')
          dicts_lists.sort(key=f)

          №4:對(duì)字符串列表進(jìn)行排序

          我們經(jīng)常面臨包含字符串的列表,我們需要按字母順序、長度或我們想要或我們的應(yīng)用程序需要的任何其他因素對(duì)這些列表進(jìn)行排序

          my_list = ["blue""red""green"]

          #1- Using sort or srted directly or with specifc keys
          my_list.sort() #sorts alphabetically or in an ascending order for numeric data 
          my_list = sorted(my_list, key=len) #sorts the list based on the length of the strings from shortest to longest. 
          # You can use reverse=True to flip the order

          #2- Using locale and functools 
          import locale
          from functools import cmp_to_key
          my_list = sorted(my_list, key=cmp_to_key(locale.strcoll)) 

          №5:根據(jù)另一個(gè)列表對(duì)列表進(jìn)行排序

          有時(shí),我們可能需要使用一個(gè)列表來對(duì)另一個(gè)列表進(jìn)行排序,因此,我們將有一個(gè)數(shù)字列表(索引)和一個(gè)我們想使用這些索引進(jìn)行排序的列表

          a = ['blue''green''orange''purple''yellow']
          b = [32541]
          #Use list comprehensions to sort these lists
          sortedList =  [val for (_, val) in sorted(zip(b, a), key=lambda x: \
                    x[0])]

          №6:將列表映射到字典

          列表代碼片段的最后一個(gè)任務(wù),如果給定一個(gè)列表并將其映射到字典中,也就是說,我們想將我們的列表轉(zhuǎn)換為帶有數(shù)字鍵的字典

          mylist = ['blue''orange''green']
          #Map the list into a dict using the map, zip and dict functions
          mapped_dict = dict(zip(itr, map(fn, itr)))

          Dictionary Snippets

          現(xiàn)在處理的數(shù)據(jù)類型是字典

          №7:合并兩個(gè)或多個(gè)字典

          假設(shè)我們有兩個(gè)或多個(gè)字典,并且我們希望將它們?nèi)亢喜橐粋€(gè)具有唯一鍵的字典

          from collections import defaultdict
          #merge two or more dicts using the collections module
          def merge_dicts(*dicts):
            mdict = defaultdict(list)
            for dict in dicts:
              for key in dict:
                res[key].append(d[key])
            return dict(mdict)

          №8:反轉(zhuǎn)字典

          一個(gè)非常常見的字典任務(wù)是如果我們有一個(gè)字典并且想要翻轉(zhuǎn)它的鍵和值,鍵將成為值,而值將成為鍵

          當(dāng)我們這樣做時(shí),我們需要確保沒有重復(fù)的鍵。值可以重復(fù),但鍵不能,并確保所有新鍵都是可以 hashable 的

          my_dict = {
            "brand""Ford",
            "model""Mustang",
            "year"1964
          }
          #Invert the dictionary based on its content
          #1- If we know all values are unique.
          my_inverted_dict = dict(map(reversed, my_dict.items()))

          #2- If non-unique values exist
          from collections import defaultdict
          my_inverted_dict = defaultdict(list)
          {my_inverted_dict[v].append(k) for k, v in my_dict.items()}

          #3- If any of the values are not hashable
          my_dict = {value: key for key in my_inverted_dict for value in my_inverted_dict[key]}

          String Snippets

          接下來是字符串的處理

          №9:使用 f 字符串

          格式化字符串可能是我們幾乎每天都需要完成的一項(xiàng)任務(wù),在 Python 中有多種方法可以格式化字符串,使用 f 字符串是比較好的選擇

          #Formatting strings with f string.
          str_val = 'books'
          num_val = 15
          print(f'{num_val} {str_val}'# 15 books
          print(f'{num_val % 2 = }'# 1
          print(f'{str_val!r}'# books

          #Dealing with floats
          price_val = 5.18362
          print(f'{price_val:.2f}'# 5.18

          #Formatting dates
          from datetime import datetime;
          date_val = datetime.utcnow()
          print(f'{date_val=:%Y-%m-%d}'# date_val=2021-09-24

          №10:檢查子串

          一項(xiàng)非常常見的任務(wù)就是檢查字符串是否在與字符串列表中

          addresses = ["123 Elm Street""531 Oak Street""678 Maple Street"]
          street = "Elm Street"

          #The top 2 methods to check if street in any of the items in the addresses list
          #1- Using the find method
          for address in addresses:
              if address.find(street) >= 0:
                  print(address)

          #2- Using the "in" keyword 
          for address in addresses:
              if street in address:
                  print(address)

          №11:以字節(jié)為單位獲取字符串的大小

          有時(shí),尤其是在構(gòu)建內(nèi)存關(guān)鍵應(yīng)用程序時(shí),我們需要知道我們的字符串使用了多少內(nèi)存

          str1 = "hello"
          str2 = "??"

          def str_size(s):
            return len(s.encode('utf-8'))

          str_size(str1)
          str_size(str2)

          Input/ Output operations

          最后我們來看看輸入輸出方面的代碼片段
          №12:檢查文件是否存在
          在數(shù)據(jù)科學(xué)和許多其他應(yīng)用程序中,我們經(jīng)常需要從文件中讀取數(shù)據(jù)或向其中寫入數(shù)據(jù),但要做到這一點(diǎn),我們需要檢查文件是否存在,因此,我們需要確保代碼不會(huì)因 IO 錯(cuò)誤而終止

          #Checking if a file exists in two ways
          #1- Using the OS module
          import os 
          exists = os.path.isfile('/path/to/file')

          #2- Use the pathlib module for a better performance
          from pathlib import Path
          config = Path('/path/to/file'
          if config.is_file(): 
              pass

          №13:解析電子表格

          另一種非常常見的文件交互是從電子表格中解析數(shù)據(jù),我們使用 CSV 模塊來幫助我們有效地執(zhí)行該任務(wù)

          import csv
          csv_mapping_list = []
          with open("/path/to/data.csv"as my_data:
              csv_reader = csv.reader(my_data, delimiter=",")
              line_count = 0
              for line in csv_reader:
                  if line_count == 0:
                      header = line
                  else:
                      row_dict = {key: value for key, value in zip(header, line)}
                      csv_mapping_list.append(row_dict)
                  line_count += 1

          好了,我們一起學(xué)習(xí)了 13 個(gè)代碼片段,這些片段簡單、簡短且高效,無論我們?cè)谀膫€(gè)應(yīng)用程序領(lǐng)域工作,最終都會(huì)在相應(yīng)的 Python 項(xiàng)目中至少使用其中的一個(gè),所以收藏就是最好的選擇!

          好了,今天的分享就到這里,喜歡就點(diǎn)個(gè)吧!

          原文地址:https://towardsdatascience.com/13-useful-python-snippets-that-you-need-to-know-91580af9b1f6

          往期精彩回顧





          瀏覽 100
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          評(píng)論
          圖片
          表情
          推薦
          點(diǎn)贊
          評(píng)論
          收藏
          分享

          手機(jī)掃一掃分享

          分享
          舉報(bào)
          <kbd id="afajh"><form id="afajh"></form></kbd>
          <strong id="afajh"><dl id="afajh"></dl></strong>
            <del id="afajh"><form id="afajh"></form></del>
                1. <th id="afajh"><progress id="afajh"></progress></th>
                  <b id="afajh"><abbr id="afajh"></abbr></b>
                  <th id="afajh"><progress id="afajh"></progress></th>
                  日韩精品免费在线观看 | 国产亚洲无码在线观看 | av夜夜撸| 伊人操逼 | 亚洲天堂一区二区 |