首頁  >  文章  >  後端開發  >  如何在Python中將字典轉換為矩陣或nArray?

如何在Python中將字典轉換為矩陣或nArray?

王林
王林轉載
2023-08-27 21:33:081287瀏覽

如何在Python中將字典轉換為矩陣或nArray?

在本文中,我們將向您展示如何使用Python的NumPy函式庫中的array()函數將字典轉換為矩陣或NumPy陣列。

有時候需要將Python中的字典轉換為NumPy數組,Python提供了一種高效的方法來實現這一點。將字典轉換為NumPy陣列會得到一個包含字典中鍵值對的陣列。

在這個部分,我們將看一些在Python中將各種類型的字典轉換為NumPy陣列的範例

  • 將字典轉換為Numpy陣列
  • 將巢狀字典轉換為Numpy陣列
  • 將具有混合鍵的字典轉換為Numpy陣列

numpy.array() 函數

它回傳一個 ndarray。 ndarray 是滿足給定要求的陣列物件。

要將字典轉換為NumPy數組,Python提供了numpy.array()方法,但我們必須先做一些準備。請依照以下三個基本步驟作為前期任務。

  • 首先,使用dict.items()來取得字典中的一組鍵值對。
  • 然後,將這個群組作為一個對象,使用 list(obj) 將其轉換為一個清單。
  • 最後,使用這個列表作為數據,呼叫 numpy.array(data) 將其轉換為陣列。

文法

numpy.array(object, dtype = None, *, copy = True, order = ‘K’, subok = False, ndmin = 0)

參數

  • object − 這是一個陣列或任何暴露陣列介面的物件。

  • dtype − 陣列的首選資料類型。

  • copy − 如果為true(預設值),則複製該項。否則,只有當__array__回傳一個副本時才會產生副本

  • #order − 它表示陣列的記憶體佈局

  • subok − 如果為true,則子類別會被傳遞;否則,傳回的陣列會被強制轉換為基底類別數組(預設)

  • #ndmin − 指示結果陣列的最小維數。

  • Return Value − 傳回一個ndarray(它是滿足指定要求的陣列物件)

#將字典轉換為Numpy陣列

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用import關鍵字,匯入具有別名(np)的numpy模組。

  • 建立一個變數來儲存輸入的字典。

  • items() 函數(傳回字典中的鍵值對組)套用到輸入的字典,以取得字典中的所有鍵值對,並建立一個變數來儲存它。

  • 使用list()函數(傳回一個可迭代物件的列表),將字典的所有鍵值對轉換為列表資料型別。

  • 使用NumPy模組的array()函數(傳回一個ndarray。ndarray是滿足給定要求的陣列物件),將上述資料清單轉換為NumPy陣列。

  • 將輸入字典轉換後的NumPy陣列印出來。

Example

以下程式使用array()函數將輸入的字典轉換為NumPy數組,並傳回它 -

# importing numpy module with an alias name
import numpy as np

# creating a dictionary
inputDict = {1: 'Hello',
2: 'Tutorialspoint',
3: 'python'}

# getting all the key-value pairs in the dictionary
result_keyvalpairs = inputDict.items()

# converting an object to a list
list_data = list(result_keyvalpairs)

# converting list to an numpy array using numpy array() function
numpy_array = np.array(list_data)
print("Input Dictionary =",inputDict)

# printing the resultant numpy array
print("The resultant numpy array:\n", numpy_array)

輸出

執行時,上述程式將產生以下輸出

Input Dictionary = {1: 'Hello', 2: 'Tutorialspoint', 3: 'python'}
The resultant numpy array:
 [['1' 'Hello']
 ['2' 'Tutorialspoint']
 ['3' 'python']]

將巢狀字典轉換為Numpy陣列

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 建立一個變數來儲存一個輸入的巢狀字典(一個字典中包含另一個字典)。

  • 使用 list() 函數(傳回可迭代物件的清單)將字典的所有巢狀鍵值對轉換為清單資料類型。

  • 使用NumPy模組的array()函數將上述資料列表轉換為NumPy陣列。

  • 將輸入字典轉換後的NumPy陣列印出來。

Example

以下程式使用array()函數將巢狀輸入字典轉換為NumPy數組,並傳回它

# importing NumPy module with an alias name
import numpy as np

# creating a nested dictionary
nestedDictionary = {1: 'Hello',
                    2: 'Tutorialspoint',
                    3: {'X': 'This is',
                        'Y': 'python',
                        'Z': 'code'}}

# getting all the key-value pairs in the dictionary
result_keyvalpairs = nestedDictionary.items()

# converting an object to a list
list_data = list(result_keyvalpairs)

# converting list to an array using numpy array() function
numpy_array = np.array(list_data)
print("Input nested Dictionary = ",nestedDictionary)

# printing the resultant numpy array
print("\nThe resultant numpy array:\n", numpy_array)

輸出

執行時,上述程式將產生以下輸出

Input nested Dictionary =  {1: 'Hello', 2: 'Tutorialspoint', 3: {'X': 'This is', 'Y': 'python', 'Z': 'code'}}

The resultant numpy array:
 [[1 'Hello']
   [2 'Tutorialspoint']
   [3 {'X': 'This is', 'Y': 'python', 'Z': 'code'}]]

將具有混合鍵的字典轉換為Numpy陣列

建立一個輸入字典,其中包含字串、整數、浮點數、列表等混合鍵,並用隨機值填滿它。

Example

以下程式使用array()函數將具有混合鍵的字典轉換為NumPy數組,並傳回它−

# importing numpy module with an alias name
import numpy as np

# creating a dictionary with mixed keys(like string and numbers as keys)
nestedDictionary = {'website': 'Tutorialspoint', 10: [2, 5, 8]}

# getting all the key-value pairs in the dictionary
result_keyvalpairs = nestedDictionary.items()

# converting an object to a list
list_data = list(result_keyvalpairs)

# converting list to an array using numpy array() function
numpy_array = np.array(list_data, dtype=object)

# printing the resultant numpy array
print("The resultant numpy array:\n", numpy_array)

輸出

執行時,上述程式將產生以下輸出

The resultant numpy array:
 [['website' 'Tutorialspoint']
   [10 list([2, 5, 8])]]

結論

在本文中,我們學習了字典中各種類型的鍵值對以及如何將它們轉換為矩陣或Numpy數組。

以上是如何在Python中將字典轉換為矩陣或nArray?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除