从列表中删除双引号

时间:2014-06-25 17:54:44

标签: python csv sage

我使用sage,python和CSV。

以下是我的csv文件中的示例行:

"(4, 4)",0.921,1.512,1.718,"[[(0, 0, 1), (1, 0, 0)]]","[[(0, 0, 3), (1, 0, 0)]]"

我也有:

with open('log.csv', 'rt') as logFile:
    logreader = csv.reader(logFile)
    for row in logreader:
        a = row[3]
        b = row[4]

我希望csv.reader在分配ab时删除双引号,以便:{/ p>

a == [[(0, 0.5, 1), (1, 0, 0)]]
b == [[(0, 0, 3), (1, 0, 0)]]

然而

a == "[[(0, 0, 1), (1, 0, 0)]]"
b == "[[(0, 0, 3), (1, 0, 0)]]"

实现我期望的最佳方式是什么? 感谢

2 个答案:

答案 0 :(得分:4)

您需要使用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])

参见下面的演示:

>>> 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'>
>>>

答案 1 :(得分:0)

我会使用内置的strip功能:

a = row[3].strip('"')
b = row[4].strip('"')