[英]Strip double quotes from list
I'm using sage, python and CSV. 我正在使用鼠尾草,python和CSV。
Here is an example row from my csv file: 这是我的csv文件中的示例行:
"(4, 4)",0.921,1.512,1.718,"[[(0, 0, 1), (1, 0, 0)]]","[[(0, 0, 3), (1, 0, 0)]]"
I also have: 我也有:
with open('log.csv', 'rt') as logFile:
logreader = csv.reader(logFile)
for row in logreader:
a = row[3]
b = row[4]
I was expecting csv.reader
to strip the double-quotes when assigning a
and b
such that: 我期望csv.reader
在分配a
和b
时csv.reader
双引号,使得:
a == [[(0, 0.5, 1), (1, 0, 0)]]
b == [[(0, 0, 3), (1, 0, 0)]]
however 然而
a == "[[(0, 0, 1), (1, 0, 0)]]"
b == "[[(0, 0, 3), (1, 0, 0)]]"
What is the best way to achieve what I was expecting? 实现我所期望的最佳方法是什么? Thanks 谢谢
You need to use ast.literal_eval
to parse the strings into lists: 您需要使用ast.literal_eval
将字符串解析为列表:
from ast import literal_eval
with open('log.csv', 'rt') as logFile:
logreader = csv.reader(logFile)
for row in logreader:
a = literal_eval(row[3])
b = literal_eval(row[4])
See a demonstration below: 请参见下面的演示:
>>> from ast import literal_eval
>>> literal_eval("[[(0, 0, 1), (1, 0, 0)]]")
[[(0, 0, 1), (1, 0, 0)]]
>>> type(literal_eval("[[(0, 0, 1), (1, 0, 0)]]"))
<class 'list'>
>>>
I would use the built-in strip function: 我将使用内置的剥离功能:
a = row[3].strip('"')
b = row[4].strip('"')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.