如何將Python的CSV字串轉換為陣列?
在這篇文章中,我們將瞭解如何將CSV字串轉換為陣列。
第一種方法是使用split()方法。此方法接受一個引數,並以此字元作為分隔符來分割字串。由於輸入是CSV,它是逗號分隔的,我們將設定逗號作為分隔符並將字串分割成陣列。
Python中的split()方法是一個字串操作函式,它將較大的字串分割成多個較小的字串。split()方法將這些字串作為列表返回。
示例
在下面的示例中,我們使用CSV字串作為輸入,並將其轉換為陣列 −
str1 = "Hello,Everyone,Welcome,to,Tutorialspoint" print("The given CSV string is") print(str1) print("Converting the given CSV string into array") res = list(map(str.strip, str1.split(','))) print(res)
輸出
以上示例的輸出如下所示 −
The given CSV string is Hello,Everyone,Welcome,to,Tutorialspoint Converting the given CSV string into array ['Hello', 'Everyone', 'Welcome', 'to', 'Tutorialspoint']
使用inner.split()和splitlines()
第二種方法是使用inner.split()和splitlines()。如果輸入的CSV字串是多行的,則使用此方法。在這種情況下,我們應該首先分割行,因此我們將使用splitlines()方法在新行字元處進行分割。在新行分割後,我們應該使用inner.split()方法以逗號分割每一行,然後我們將它們組合成一個列表。
示例
在下面的示例中,我們使用多行CSV字串作為輸入,並使用inner.split()和splitlines()方法將其轉換為陣列 −
s = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA" print("The given CSV string is") print(s) print("Converting the given CSV string into array") res = list(map(str.strip, s_inner.split(',')) for s_inner in s.splitlines()) print((res))
輸出
以上示例的輸出如下所示 −
The given CSV string is 1, John Doe, Boston, USA 2, Jane Doe, Chicago, USA Converting the given CSV string into array [<map object at 0x7f8074f002b0>, <map object at 0x7f8074f00390>]
使用csv庫的reader()方法
第三種方法是使用csv庫的reader()方法。此方法接受CSV字串作為輸入並將其轉換為陣列。此方法也可用於多行輸出,但我們必須使用splitlines()方法轉換多行。
示例
在下面的示例中,我們使用CSV字串作為輸入,並使用reader()方法將其轉換為陣列 −
import csv str1 = "1, John Doe, Boston, USA\n2, Jane Doe, Chicago, USA".splitlines() print("The given CSV string is") print(str1) print("Converting the given CSV string into array") x = csv.reader(str1) print(list(x))
輸出
以上示例的輸出如下所示 −
The given CSV string is ['1, John Doe, Boston, USA', '2, Jane Doe, Chicago, USA'] Converting the given CSV string into array [['1', ' John Doe', ' Boston', ' USA'], ['2', ' Jane Doe', ' Chicago', ' USA']]
廣告