如何从不带引号的CSV文件创建元组?

时间:2018-11-20 05:39:07

标签: python list csv tuples

我正在读取CSV文件,需要创建元组,但是我需要删除引号。 CSV行示例:

57, 47, 1.04
1288, 317, 1.106
149, 84, 1.05

我尝试过

import csv
from pprint import pprint

with open('./Documents/1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = list(map(tuple, reader))

结果为:

[('57', '47', '1.04'),
 ('1288', '317', '1.106'),
 ('149', '84', '1.05')]

我需要成为它

[(57, 47, 1.04183),
 (1288, 317, 1.106),
 (149, 84, 1.05)]

发现了类似的问题here,但仍无法找到答案。

3 个答案:

答案 0 :(得分:1)

这需要添加额外的处理,并通过类型转换进行转换:

reader = csv.reader(file, skipinitialspace=True)
# if the file has a header
# header = next(reader)
rows = [[float(row[0]), float(row[1]), float(row[2])] for row in reader]
print rows

答案 1 :(得分:1)

您可以使用ast.literal_eval()将元组内的数字转换为它们各自的类型:

import csv
from ast import literal_eval
from pprint import pprint

with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   x = [tuple(map(literal_eval, x)) for x in map(tuple, reader)]
   print(x)
   # [(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]

答案 2 :(得分:0)

def num(s):
        try:
            return int(s)
        except ValueError:
            return float(s)


with open('1.csv', encoding='utf-8-sig') as file:
   reader = csv.reader(file, skipinitialspace=True)
   output = [tuple(map(num, x)) for x in map(tuple, reader)]
   print(output)

输出:

[(57, 47, 1.04), (1288, 317, 1.106), (149, 84, 1.05)]