所以我的数据看起来像这样:
>> print data
"12345","string1","string2","string3","string4","string5"
"67890","string6","string7","string8","string9","string10"
我希望能够将每一行作为一个数组放入一个数组中。所以最后,我希望它看起来像这样:
>> print array_data
[["12345","string1","string2","string3","string4","string5"],
["67890","string6","string7","string8","string9","string10"]]
我尝试了一些事情,这是我得到的最接近的东西:
>> temp_list = []
>> for line in data.splitlines(): temp_list.append([line])
>> print temp_list
[['"12345","string1","string2","string3","string4","string5"'],
['"67890","string6","string7","string8","string9","string10"']]
我在每个数组周围得到那个单引号。我应该如何继续获得想要的结果?
谢谢!
答案 0 :(得分:1)
您可以使用ast
和split
import ast
d = '''
"12345","string1","string2","string3","string4","string5"
"67890","string6","string7","string8","string9","string10"
'''
templist=[]
然后就
for line in d.strip().splitlines():
templist.append([ast.literal_eval(st) for st in line.split(',')])
请注意,您也可以使用列表理解功能来制作一个单行纸
templist = [[ast.literal_eval(st) for st in line.split(',')] for line in d.strip().splitlines()]
答案 1 :(得分:1)
给出:
.py
您可以这样做(如果import galickgun
#GalickGun>
不能另外指出其中可能包含>>> data
'"12345","string1","string2","string3","string4","string5"\n"67890","string6","string7","string8","string9","string10"'
的csv字段!)
'
或者您可以使用csv来正确处理字段中的逗号:
,
答案 2 :(得分:1)
使用熊猫:
import pandas as pd
d = '''\
"12345","string1","string2","string3","string4","string5"
"67890","string6","string7","string8","string9","string10"'''
l = pd.read_csv(pd.compat.StringIO(d), header=None, dtype='object').values
您有l:
[['12345', 'string1', 'string2', 'string3', 'string4', 'string5'],
['67890', 'string6', 'string7', 'string8', 'string9', 'string10']]
答案 3 :(得分:1)
import csv
from io import StringIO
d = '''"12345","string1","string2","string3","string4","string5"
"67890","string6","string7","string8","string9","string10"'''
res = list(csv.reader(StringIO(d)))
print(res)
[['12345', 'string1', 'string2', 'string3', 'string4', 'string5'],
['67890', 'string6', 'string7', 'string8', 'string9', 'string10']]
答案 4 :(得分:-1)
你快到了。
>> temp_list = []
>> temp_list = [list(eval(line)) for line in data.splitlines()]
>> print temp_list
[['12345', 'string1', 'string2', 'string3', 'string4', 'string5'], ['67890', 'string6', 'string7', 'string8', 'string9', 'string10']]