如何將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']]

更新於:2022年12月7日

15K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告