返回元素中各行組成的列表,在 NumPy 中按行邊界分割


要返回元素中各行組成的列表,按行邊界分割,請在 Python NumPy 中使用 **numpy.char.splitlines()** 方法。第一個引數是輸入陣列。

keepends 引數表示除非指定 keepends 為 True,否則換行符不包含在結果列表中。splitlines() 函式返回一個列表物件陣列。

numpy.char 模組為 numpy.str_ 或 numpy.bytes_ 型別陣列提供了一組向量化的字串操作。

步驟

首先,匯入所需的庫:

import numpy as np

建立一個數組:

arr = np.array(["Bella
Cio", "Brad
Pitt", "Katie
Perry"])

顯示我們的陣列:

print("Array...
",arr)

獲取資料型別:

print("
Array datatype...
",arr.dtype)

獲取陣列的維度:

print("
Array Dimensions...
",arr.ndim)

獲取陣列的形狀:

print("
Our Array Shape...
",arr.shape)

獲取陣列的元素個數:

print("
Elements in the Array...
",arr.size)

要返回元素中各行組成的列表,按行邊界分割,請使用 numpy.char.splitlines() 方法:

print("
Result...
",np.char.splitlines(arr))

示例

import numpy as np

# Create an array
arr = np.array(["Bella
Cio", "Brad
Pitt", "Katie
Perry"]) # Displaying our Array print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To return a list of the lines in the element, breaking at line boundaries, use the numpy.char.splitlines() method in Python Numpy # The 1st parameter is the input array print("
Result...
",np.char.splitlines(arr))

輸出

Array...
['Bella
Cio' 'Brad
Pitt' 'Katie
Perry'] Array datatype... <U11 Array Dimensions... 1 Our Array Shape... (3,) Elements in the Array... 3 Result... [list(['Bella', 'Cio']) list(['Brad', 'Pitt']) list(['Katie', 'Perry'])]

更新於:2022年2月17日

69 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告