如何将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']]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP